Vue3.0 +Typescript

在typescript环境下,vue的属性、事件等写法有很大的不同,在这里做一个总结:

import { Component,Vue, Prop, Emit , Watch } from 'vue-property-decorator';

一、计算属性

javascript

computed: {
        // 计算属性的 getter
    reversedMessage: function () {
      return this.message.split('').reverse().join('')
    }
}

typescript

//  这里面的‘chatacctSex’不用另外定义,可以直接用

get chatacctSex() {
    if(this.accountDetail.idcardCode !=='') {
        if(Number((this.accountDetail.idcardCode).split('')[16])%2 === 0) {
               return '女'
           } else if (Number((this.accountDetail.idcardCode).split('')[16])%2 === 1) {
               return '男'
           }
        } else {
           return '未知'
   }
}

 二、Watch

javascript

var vm = new Vue({
  data: {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: {
      f: {
        g: 5
      }
    }
  },
  watch: {
    a: function (val, oldVal) {
      console.log('new: %s, old: %s', val, oldVal)
    },
    // 方法名
    b: 'someMethod',
    // 深度 watcher
    c: {
      handler: function (val, oldVal) { /* ... */ },
      deep: true
    },
    // 该回调将会在侦听开始之后被立即调用
    d: {
      handler: function (val, oldVal) { /* ... */ },
      immediate: true
    },
    e: [
      function handle1 (val, oldVal) { /* ... */ },
      function handle2 (val, oldVal) { /* ... */ }
    ],
    // watch vm.e.f's value: {g: 5}
    'e.f': function (val, oldVal) { /* ... */ }
  }
})
vm.a = 2 // => new: 2, old: 1

typescript

这里onchange可以写在需要监听的属性前面,也可以写在后面

@Watch('refreshTime')
private refreshTimeOnChange(newVal: number) {
   console.info(newVal) 
}

三、父子组件传值

1、emit (子组件向父组件传值)

javascript

/** 子组件 */

// 第一个参数是自定义的事件名称,第二个需要上传到父组件的参数

this.$emit('resetExpireTime',this.expireTime)

/** 父组件 */

<temp-on-off @resetExpireTime="onResetExpireTime"></temp-on-off>

onResetExpireTime:function(value) {
   console.info(value)
}

typescript

/** 子组件 */

@Emit()
private manuallyRefresh(refreshTime: number,msgId: string) {
    console.info('Emit manuallyRefresh')

}

/** 父组件 */

//  这里需要注意的是,父组件里面@后面的事件名称需要将驼峰命名改成‘-’连接

<message-report @manually-refresh='onManuallyRefresh'/>

private onManuallyRefresh(time: number,msgId: string) {
    this.refreshmsgId = msgId
    this.refreshTime = time

}

2、prop (父组件向子组件传值) 

 javascript

/** 父组件 */

<talk-trend :date="talkTrend.talkDate"/>

/** 子组件*/

props:['date']

created() {
  console.info(this.date)
}

 typescript

/** 父组件 */
// 给父组件添加属性

<message-report :source="messageSource" @manually-refresh='onManuallyRefresh'/>

private  messageSource: string = 'chat'


/** 子组件 */

@Prop({ default: '' })
private source: string;

private created() {
   console.info(this.source)
}

猜你喜欢

转载自blog.csdn.net/caroline_Luoluo/article/details/83820250