這篇文章將為大家詳細講解有關vue組件化的實例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
全局組件
<!DOCTYPE html> <html> <head> <title>vue</title> <!-- <script src="./vue.js"></script> --> <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> </head> <body> <div id="root"> <input v-model="inputValue"/> <button @click="addTextFunc">提交</button> <ul> <todo-item v-bind:content="item" v-for="item in list"></todo-item> </ul> </div> <script> //全局組件 Vue.component("TodoItem", { props: ["content"], template: "<li>{{content}}</li>" }) var app = new Vue({ el: "#root", data: { list: [] }, methods: { addTextFunc: function() { this.list.push(this.inputValue) this.inputValue = "" } } }); </script> </body> </html>
局部組件
<!DOCTYPE html>
<html>
<head>
<title>vue</title>
<!-- <script src="./vue.js"></script> -->
<script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script>
</head>
<body>
<div id="root">
<input v-model="inputValue"/>
<button @click="addTextFunc">提交</button>
<ul>
<todo-item v-bind:content="item" v-for="item in list"></todo-item>
</ul>
</div>
<script>
//局部組件
var TodoItem = {
props: ['content'],
template: "<li>{{content}}</li>"
}
var app = new Vue({
el: "#root",
//注冊TodoItem組件
components: {
TodoItem: TodoItem //命名叫TodoItem,在實例中也叫TodoItem
},
data: {
list: []
},
methods: {
addTextFunc: function() {
this.list.push(this.inputValue)
this.inputValue = ""
}
}
});
</script>
</body>
</html>子組件、父組件雙向傳遞數據
<!DOCTYPE html>
<html>
<head>
<title>vue</title>
<script src="./vue.js"></script>
<!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="root">
<input v-model="inputValue"/>
<button @click="addTextFunc">提交</button>
<ul>
"v-bind:"可以簡寫為":"
<todo-item v-bind:content="item" v-bind:index="index" v-for="(item, index) in list" @delete="handleItemDelete"></todo-item>
</ul>
</div>
<script>
//局部組件
var TodoItem = {
props: ['content', 'index'], //要使用就要聲明(父組件給子組件傳值,子組件要接收!)
//v-on:click的簡寫:@click
template: "<li @click='handleItemClick'>{{content}}</li>",
methods: {
handleItemClick() {
//子組件向父組件傳值(觸發事件,父組件的@delete="handleItemDelete"在監聽)
this.$emit("delete", this.index); //不但觸發delete時間,同時還把this.index作為參數給父組件
}
}
}
var app = new Vue({
el: "#root",
//注冊TodoItem組件
components: {
TodoItem: TodoItem //命名叫TodoItem,在實例中也叫TodoItem
},
data: {
list: []
},
methods: {
addTextFunc: function() {
this.list.push(this.inputValue)
this.inputValue = ""
},
handleItemDelete: function(index) { //此處接收傳過來的this.index
//全部刪除
//this.list = []
//刪除點擊的數據(標識為當前數據的index)
this.list.splice(index, 1)
}
}
});
</script>
</body>
</html>關于“vue組件化的實例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。