【问题标题】:how to render a template in vuejs如何在 vuejs 中渲染模板
【发布时间】:2018-01-12 10:23:00
【问题描述】:

我正在使用 2.3.4 版本的 jQuery 和 vuejs:

https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js

我有以下代码:

      // initialize the vue.
      vueVar = new Vue({
        el: '#content',
        methods: {
          // Start by creating a function to inject a menu link to the dom.
          inject_menu_link: function (menu_title, menu_url, menu_type) {
            if($(menu_type + ' li').length){
              // if the menu exists
              template = '<menuLinkTpl v-bind:url="'+menu_url+'" v-bind:name="'+menu_title+'"></menuLinkTpl>';
              $(menu_type + ' > li').last().after(template);
            }
          },
        },
        components: {
          // make a menu template to add; given the url and the title of the menu
          'menuLinkTpl': {
            props: [{
              // menu link url
              url: '',
              // menu link name
              name: '',
            }],
            template: '<li><a v-bind:href="\'/\'+ url " v-bind:title="name">{{name}}</a></li>',
          },
        },
      });
<body>
  <div id="content">
    <ul id="block-menu">
      <li><a>menu 1</a></li>
      <li><a>menu 2</a></li>
    </ul>
  </div>
</body>

我想要实现的是能够在菜单中添加一个新的菜单项 每当调用函数vueVar.inject_menu_link('menu link title', 'url-test', '#block-menu')

现在发生了什么是:

&lt;menuLinkTpl v-bind:menuurl="/url-test" v-bind:menuname="menu link title"&gt;&lt;/menuLinkTpl&gt;

这是附加到 dom 而不渲染的内容。

我该如何解决这个问题?

【问题讨论】:

  • 这是一种类似 jQuery 的方法,它不是任何 MVC/MVVM 框架/库(例如 Vue.js)应该采用的方式。当您在列表中添加或删除项目时,停止思考 DOM 元素,开始思考 Vue 迭代和更新的列表。

标签: jquery html vue.js


【解决方案1】:

我建议为此使用v-for

export default {
    data () {
         return  {
             menuItems: [{ .. initial value ...} ]
         }
    },
    methods: {
        injectMenu () {
            menuItems.push({}).
        }
    }
}

在模板中:

<body>
  <div id="content">
    <ul id="block-menu">
      <li is="menuLinkTpl" v-for="menu in menuItems" :url="menu. ..." :name="menu. ..."></li>
    </ul>
  </div>
</body>

不应该使用带有 vue 的文本来动态添加内容。这是因为 vue 需要创建一个虚拟 DOM 以获得更好的性能。请参阅https://vuejs.org/v2/guide/render-function.html 如果您仔细阅读文档,您可以使用createElement 并模仿您的文本注入。

【讨论】:

    猜你喜欢
    • 2020-04-23
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2018-10-20
    • 2019-01-29
    • 2019-01-11
    相关资源
    最近更新 更多