前端开发那些事儿

VUE 计算属性/监听/方法/样式/插槽/组件/v-once/

2020-11-05  本文已影响0人  阿鲁提尔
1.Vue 实例
<div id="root">{{message}}</div>

let vm = new Vue({
    el: '#root',
    data:{
        message: 'hellow world'
    }
}) 
创建一个vue实例  接管id为root的dom
定义一个组件
<item><item>

Vue.component('item', {
  template: '<div>heloo world</div>'
})

Vue的底层也会把component转换成 new Vue 实例
vm.$destroy()
2.Vue 计算属性,方法和侦听器
计算属性

{{fullName}}

data:{
    firstName: 'Jack',
    lastName:'Lee',
},
computed:{
    fullName: function() {
        return this.firstName + ' ' + this.lastName
    }
}

计算属性非常重要的点:内置缓存,如果依赖的变量没有发生变化,计算属性就不会发生计算,用上次缓存的结果
{{fullName()}}

methods:{
  fullName: function(){
    return this.firstName + " " + this.lastName
  }
}

只要修改变量,方法就会执行一次,不论改变的是不是依赖的变量
data:{
  firstName:"jack",
  lastName:"Lee",
  fullName:"Dell lee",
  age: 28
},
watch:{
  firstName:function(){
    this.fullName=this.firstName + ' ' + this.lastName
  },
  lastName:function(){
    this.fullName=this.firstName + ' ' + this.lastName
  }
}
3.Vue 计算属性的setter和getter
data:{
  firstName:"jack",
  lastName:"Lee"
},
computed:{
  fullName:{
    get:function(){
      return this.firstName + " " + this.lastName
    },
    set:function(value){
      let arr = value.split(" ");
      this.firstName = arr[0];
      this.lastName = arr[1];
    }
  }
}
4.Vue 中的样式绑定
1. 根据变量显示class名
  :class="{activated: isActivated}"
2. 直接给变量添加class名
  :class="[activated,activatedOne]"
  data:{
    activated:"",
    activatedOne:"activated-one"
  }
3. 样式写成对象
  :style="styleObj"
  data:{
    styleObj: {
        color: "red"
    }
  }
  4. 样式写成数组
  :style="[styleObj,{fontSize: '20px' }]"
  data:{
    styleObj: {
        color: "red"
    }
  }
5.Vue 中使用插槽
不使用插槽时
<div id="root">
    <child content="<p>22222</p><p>22222</p><p>22222</p><p>22222</p>"></child>
</div>
<script>
  Vue.component('child', {
    props: ['content'],
    template: `<div>
                 <p>hello</p>
                 <div v-html="content"></div>
               </div>`
  })
  var vm = new Vue({
      el: '#root',
  })
</script>

优雅的使用插槽
<div id="root">
  <child></child>
</div>
<script>
  Vue.component('child', {
    template: `<div>
        <p>hello</p>
        <slot>默认内容</slot>  // 如果不写内容 就会显示默认内容
      </div>
    `,
  })
  var vm = new Vue({
    el: '#root',
  })
</script>

多个插槽同时使用(具名插槽)
<div id="root">
  <body-content>
    <div class="header" slot="header">header</div>
    <div class="footer" slot="footer">footer</div>
  </body-content>
</div>
<script>
  Vue.component('body-content', {
    template: `<div>
      <slot name="header"></slot>
      <p>hello</p>
      <slot name='footer'></slot>
    </div>`,
  })
  var vm = new Vue({
    el: '#root',
  })
</script>

Vue 中的作用域插槽(自定义循环标签)
<div id="root">
  <child>
    <template slot-scope="props">
      <p>{{props.item}}</p>
    </template>
  </child>
</div>
<script>
  Vue.component('child', {
    data: function () {
      return {
        list: [1, 2, 3, 4],
      }
    },
    template: `<div>
        <ul>
          <slot v-for="item of list" :item=item></slot>  
        </ul>
      </div>`,
  })

  var vm = new Vue({
    el: '#root',
  })
</script>
6.Vue 动态组件与v-once 指令
1.利用变量v-if控制显示
<div id="root">
  <child-one v-if="type==='child-one'"></child-one>
  <child-two v-else></child-two>
  <button @click="handleClickBtn">change</button>
</div>
<script>
  Vue.component('child-one', {
    template: '<div>child-one</div>',
  })
  Vue.component('child-two', {
    template: '<div>child-two</div>',
  })
  var vm = new Vue({
    el: '#root',
    data() {
      return {
        type: 'child-one',
      }
    },
    methods: {
      handleClickBtn() {
        this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
      },
    },
  })
</script>
=========================================
2.动态组件
<div id="root">
  <component :is="type"></component>
  // 根据组件名称自动加载组件
  <button @click="handleClickBtn">change</button>
</div>
<script>
  Vue.component('child-one', {
    template: '<div>child-one</div>',
  })
  Vue.component('child-two', {
    template: '<div>child-two</div>',
  })
  var vm = new Vue({
    el: '#root',
    data() {
      return {
        type: 'child-one',
      }
    },
    methods: {
      handleClickBtn() {
        this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
      },
    },
  })
</script>
=========================================
3. v-once 指令
<div id="root" v-once>
  <child-one v-if="type==='child-one'"></child-one>
  <child-two v-else></child-two>
  <button @click="handleClickBtn">change</button>
</div>
v-once 只渲染一次 未来即使变量发生变化 也不改变
7.Vue 非父子组件传值
1. 发布订阅模式(Bus/总线/发布订阅模式/观察者模式)
  <div id="root">
    <child content="Dell"></child>
    <child content="Lee"></child>
  </div>
  Vue.prototype.bus = new Vue()
  Vue.component('child',{
    data: function(){
        return {
          selfContent: this.content
        }
    },
    props:{
        content: String
    },
    template:'<div @click="handleClick">{{selfContent}}</div>',
    methods:{
        handleClick: function(){
          this.bus.$emit('change',this.selfContent)
        }
    },
    mounted: function(){
        let _this = this
        this.bus.$on('change',function(msg){
           _this.selfContent= msg
        })
    }
  })
2. 官方提供Vuex
 · 组件调用dispatch方法来操作Actions
 · 组件/Actions调用Commit方法来操作Devtools去改变state中的数据

 · 安装与使用
  npm install vuex --save
src/store/index.js:
-------------------
 import Vue from 'vue'
 import Vuex from 'vuex'
  
 Vue.use(Vuex)

 export default new Vuex.Store({
      state:{
        city:'上海'
      }
  })


src/main.js:
-------------------
import store from './store'

创建根实例的时候 把store 传入
new Vue({
  el: '#app',
  store,
  ...
})

使用的时候  方法一:
  {{this.$store.state.city}}
修改的时候
  this.$store.dispatch('changeCity',city)

src/store/index.js:
-------------------
 import Vue from 'vue'
 import Vuex from 'vuex'
  
 Vue.use(Vuex)

 export default new Vuex.Store({
      state:{
        city:'上海'
      },
      actions: {
        changeCity (ctx,city) {
          // 调用mutations中的changeCity 
          ctx.commit('changeCity', city)
        }
      },
      mutations: {
        changeCity (state,city){
          state.city = city
        }
      }
  })
==============================
使用的时候 方法二(跳过dispatch步骤):
  {{this.$store.state.city}}
修改的时候
  this.$store.commit('changeCity',city)

src/store/index.js:
-------------------
 import Vue from 'vue'
 import Vuex from 'vuex'
  
 Vue.use(Vuex)

 export default new Vuex.Store({
      state:{
        city:'上海'
      },
      mutations: {
        changeCity (state,city){
          state.city = city
        }
      }
  })
8.Vue localStorage
有一些浏览器只使用localStorage 会报错 需要配合try catch 使用
try {
  localStorage.city = '上海'
} catch (e) {}
上一篇 下一篇

猜你喜欢

热点阅读