全局組件
<!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>