全局组件
<!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>
原文地址:https://blog.51cto.com/5660061/2418866
时间: 2024-10-01 01:24:53