vue03-全局组件

客官°小女子只卖身不卖艺 2022-05-10 00:00 315阅读 0赞

首先看下面代码

  1. <!DOCTYPE html>
  2. <html lang=en>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>Hello world</title>
  6. <script src="vue.js"></script>
  7. </head>
  8. <body>
  9. <div id="app">
  10. <!-- 双向绑定 mvvm-->
  11. <input type="text" v-model="inputValue" />
  12. <button v-on:click="handleBtnClick">提交</button>
  13. <ul>
  14. <to-do-item
  15. v-bind:content="item"
  16. v-bind:index=index
  17. v-for="(item, index) in list"
  18. @delete="handleItemDelete">
  19. </to-do-item>
  20. </ul>
  21. </div>
  22. <script>
  23. //v-bind可以简写成:
  24. //v-on可以简写成@
  25. //创建全局组件的一个方法
  26. Vue.component("ToDoItem",{
  27. props:['content',"index"],, //v-bind 绑定循环的item值,把值传进来的一种方式,外面传过来的数据接收
  28. template:"<li @click='handleItemClick'>{
  29. {content}}</li>",
  30. methods: {
  31. handleItemClick: function () {
  32. //this.$emit("delete"); //子组件向父组件传值,触发一个事件 父组件用v-on做监听@,用一个监听方法
  33. this.$emit("delete",this.index); //同时带一个参数,传给父组件
  34. }
  35. }
  36. });
  37. var app = new Vue({
  38. el: '#app',
  39. data: {
  40. list: [],
  41. inputValue: ''
  42. },
  43. methods: {
  44. handleBtnClick: function () {
  45. this.list.push(this.inputValue);
  46. this.inputValue = '';
  47. },
  48. handleItemDelete: function(index){
  49. this.list.splice(index,1); //删除
  50. }
  51. }
  52. })
  53. </script>
  54. </body>
  55. </html>

@就是v-on的缩写

: 就是v-bind的缩写

创建全局组件的方法是:

  1. Vue.component("ToDoItem",{
  2. props:['content',"index"],
  3. template:"<li @click='handleItemClick'>{
  4. {content}}</li>",
  5. methods: {
  6. handleItemClick: function () {
  7. this.$emit("delete",this.index);
  8. }
  9. }
  10. });

props: 向组件内部传值时定义的接收变量,例子中是接收item的值。 父组件向子组件传值的一种方式

template: 定义的模板的内容,这个模板也会一个vue实例,可以写vue的标签等

$emit: 触发父组件定义的delete方法,第二个参数表示传过去的参数,子组件向父组件传值的一种方式。

在父组件里面定义子组件,把content和index,传入子组件中,@delete监听子组件触发的delete事件,触发handleItemDelete方法。

  1. <to-do-item
  2. v-bind:content="item"
  3. v-bind:index=index
  4. v-for="(item, index) in list"
  5. @delete="handleItemDelete">
  6. </to-do-item>

效果:点击列表时,就会把当前点击的数据删除。

70

发表评论

表情:
评论列表 (有 0 条评论,315人围观)

还没有评论,来说两句吧...

相关阅读