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>