全局组件
- <!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>
来源: http://www.bubuko.com/infodetail-3119637.html