美文网首页
vue使用的细节

vue使用的细节

作者: A落儿 | 来源:发表于2018-11-28 16:13 被阅读0次

1.is的使用

在h5中规定<table>标签里面包裹的必须是<tr>,如果像普通组件一样在页面上直接引用<row></row>,那么模板渲染出来的会出错,解决方法就是用is,类似的标签还有<ul><li></li></ul>,<ol><li></li></ol>,<select><option></option></select>,都是通过is去解决

<table>
      <tbody>
        <tr is="row"></tr>
        <tr is="row"></tr>
        <tr is="row"></tr>
      </tbody>
    </table>

<script>
//注册一个全局组件
 Vue.component('row', {
      data: function () {
        return {
          content: "this is rows"
        }
      },
      template: '<tr><td>{{content}}</td></tr>'
    })
</script>

2.ref,通过这个对dom进行操作

在普通的html标签中,ref获取的是标签对应的dom元素,在组件中,ref获取的是子组件的引用,接下来可以对dom进行一些操作

<div ref="hello" @click="handleClick">hello world</div>
<counter ref="one" @change="handleChange">0</counter>
<counter ref="two" @change="handleChange">0</counter>
<div>{{total}}</div>
<script>
Vue.component('counter',{
      template:'<div @click="handleNumberClick">{{number}}</div>',
      data:function(){
        return {
          number:0
        }
      },
      methods:{
        handleNumberClick:function(){
          this.number++
          this.$emit('change')
        }
      }
    })

    var vm = new Vue({
      el: "#app",
      data: {
        total:0
      },
      methods:{
        handleClick:function(){
         console.log( this.$refs.hello)//<div>hello</div>
        },
        handleChange:function(){
          console.log(this.$refs.one.number)//输出counter里面的number
          console.log(this.$refs.two.number)//输出counter里面的number
          this.total = this.$refs.one.number+this.$refs.two.number
        }
       
      }
    })
</script>

3.动态组件和v-once

动态组件<component></component>标签是vue底层自带的标签,可以按需加载组件,v-once可以让组件只加载一次

<div id=app>
    <component :is="show"></component>
    <p><button @click="handleClick">change</button></p>
  </div>

  <script>

    Vue.component('child-one', {
      template: `<div v-once>child-one</div>`
    })

     Vue.component('child-two', {
      template: `<div v-once>child-two</div>`
    })

    var vm = new Vue({
      el: "#app",
      data:{
        show:'child-one'
      },
      methods:{
        handleClick:function(){
         // alert('1')
         console.log(this.show)
        //  this.show = this.show ==='child-one' ? 'child-two' : 'child-one'
          if(this.show==='child-one'){
            this.show='child-two'
          }else{
            this.show='child-one'
          }
        }
      }
    })
  </script>

相关文章

网友评论

      本文标题:vue使用的细节

      本文链接:https://www.haomeiwen.com/subject/rurbqqtx.html