使用组件细节点

  1. 使用 is 属性解决模板标签出现的 bug
  <div id="app">
    <table>
      <tbody>
        <!-- 直接使用 -->
        <!-- <row></row> -->
        <tr is="row"></tr>
      </tbody>
    </table>
  </div>
  <script>
    Vue.component('row', {
      template: "<tr><td>this is row</td></tr>"
    })
    var vm = new Vue({
      el: "#app",
    })
  </script>

这时,页面显示也是正常的,但是定义的组件出现在 table 标签外,原因是规定 tbody 标签内必须是 tr 标签,所以这里不认 自定义组件的 row 标签。解决方法是使用 is 属性,在 tbody 标签内还是用 tr 标签,但是添加 is 属性,如: <tr is="row"></tr> 。这样的标签还有 ul 、 ol 、 select 。

  1. 在子组件中定义 data 时,必须是一个函数,不能是对象
// 错误写法
    Vue.component('row', {
      data: {
        content: "this is row"
      },
      template: "<tr><td>{{content}}</td></tr>"
    })

这时页面会报错,原因就是子组件中 data 必须是函数:


// 正确写法
  Vue.component('row', {
      data: function(){
        return {
          content: "this is row"
        }
      },
      template: "<tr><td>{{content}}</td></tr>"
    })
  1. vue 中的 ref
  • 当 ref 写在如 div 标签内时,通过 this.$refs.name 获取到的是标签对应的 dom 元素
  <div id="app">
    <div ref="hello"
        @click="handleClick">
      hello word
    </div>
  </div>
  <script>
    var vm = new Vue({
      el: "#app",
      methods: {
        handleClick: function(){
          console.log(this.$refs.hello)
        }
      },
    })
  </script>

此时控制台打印出:
  • 当 ref 写在组件内时,通过 this.$refs.name 获取到的是子组件的引用
  <div id="app">
父组件监听子组件向外触发的 watch 事件,父组件执行 count 方法
    <counter ref="count1" @watch="count"></counter>
    <counter ref="count2" @watch="count"></counter>
    <div>{{total}}</div>
  </div>
  <script>
    Vue.component("counter", {
      data: function() { // 对应细节1,子组件中 data 必须是函数
        return {
          num: 0
        }
      },
      template: "<div @click='add'>{{num}}</div>", // 子组件添加点击事件
      methods: {
        add: function(){
          this.num++
          this.$emit("watch") // 子组件触发父组件的 watch 事件
        }
      }
    })
    var vm = new Vue({
      el: "#app",
      data: {
        total: 0
      },
      methods: {
        count: function(){
          this.total = this.$refs.count1.num + this.$refs.count2.num
        }
      },
    })
  </script>

这里 this.$refs.count1 就是子组件 counter 的引用

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Vue 实例 属性和方法 每个 Vue 实例都会代理其 data 对象里所有的属性:var data = { a:...
    云之外阅读 2,244评论 0 6
  • 三、组件 组件 (Component) 是 Vue.js 最强大的功能之一。组件可以扩展 HTML元素,封装可重用...
    小山居阅读 636评论 0 1
  • It's a common pattern in React to wrap a component in an ...
    jplyue阅读 3,310评论 0 2
  • 全息识人,是全维度的一种认识,阴阳太极也可用于这个体系中。人受到血脉传承、呼吸饮食、和灵魂深处自带的那一部分...
    兰的印迹阅读 598评论 0 0
  • 英语:迪斯尼神奇英语第三部分friends,二遍 Sight words第三部分二遍 积木英语19-26二遍 元音...
    熙熙妈0317阅读 91评论 0 0