vue.extend 局部注册 的应用2javascript
请注意,extend建立的是一个组件构造器,而不是一个具体的组件实例。因此他不能直接在new Vue中这样使用: new Vue({components: fuck})html
最终仍是要经过Vue.components注册才能够使用的。 vue
<!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>
5四、vue.extend 局部注册 的应用1java
请注意,在实例化extends组件构造器时,传入属性必须是propsData、而不是props哦npm
另外,不管是Vue.extend仍是Vue.component 里面的data定义都必须是函数返回对象,如 Vue.extend({data: function () {return {}}})。除了new Vue能够直接对data设置对象以外吧,如 new Vue({data: {}});app
<!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>