vue extend 的基本使用

vue.extend 局部注册 的应用2

请注意,extend创建的是一个组件构造器,而不是一个具体的组件实例。所以他不能直接在new Vue中这样使用: new Vue({components: fuck})

最终还是要通过Vue.components注册才可以使用的。 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>在Vue中注册组件</title>
</head>
<body>
<div id="app">
    <todo :todo-data="groceryList"></todo>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue " type="text/javascript"></script>
<script>
/**
 * 请注意,extend创建的是一个组件构造器,而不是一个具体的组件实例。
 * 所以他不能直接在new Vue中这样使用: new Vue({components: fuck})
 * 最终还是要通过Vue.components注册才可以使用的。 
 */

// 构建一个子组件
var todoItem = Vue.extend({
    template: ` <li> {{ text }} </li> `,
    props: {
        text: {
            type: String,
            default: ''
        }
    }
})

// 构建一个父组件
var todoWarp = Vue.extend({
    template: `
        <ul>
            <todo-item 
                v-for="(item, index) in todoData"
                v-text="item.text"
            ></todo-item>
        </ul>
    `,
    props: {
      todoData: {
          type: Array,
          default: []
      }
    },
    // 局部注册子组件
    components: {
        todoItem: todoItem
    }
})

// 注册到全局
Vue.component('todo', todoWarp)

new Vue({
    el: '#app',
    data: {
        groceryList: [
            { id: 0, text: '蔬菜' },
            { id: 1, text: '奶酪' },
            { id: 2, text: '随便其它什么人吃的东西' }
        ]
    }
})
</script>
</html>

 

54、vue.extend 局部注册 的应用1

请注意,在实例化extends组件构造器时,传入属性必须是propsData、而不是props哦

另外,无论是Vue.extend还是Vue.component 里面的data定义都必须是函数返回对象,如 Vue.extend({data: function () {return {}}})。除了new Vue可以直接对data设置对象之外吧,如 new Vue({data: {}});

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>在Vue中注册组件</title>
</head>
<body>
<div id="todoItem"></div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue" type="text/javascript"></script>
<script>

// 局部注册组件
var todoItem = Vue.extend({
  data: function () {
        return {
            todoData: [
              { id: 0, text: '蔬菜' },
              { id: 1, text: '奶酪' },
              { id: 2, text: '随便其它什么人吃的东西' }
            ]
        }
  },
  template: `
        <ul>
            <li v-for='(d, i) in todoData' :key="i">
                {{ d.text }}
            </li>
        </ul>
  `
});

// 请注意,在实例化extends组件构造器时,传入属性必须是propsData、而不是props哦
new todoItem({
  propsData: {
      todoData: [
          { id: 0, text: '蔬菜' },
          { id: 1, text: '奶酪' },
          { id: 2, text: '随便其它什么人吃的东西' }
      ]
  }
}).$mount('#todoItem')

</script>
</html>

 

posted @ 2018-02-07 09:41  贝尔塔猫  阅读(57325)  评论(2编辑  收藏  举报