版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27868061/article/details/82918205
以vue-class-component示例来看
App.vue
<template>
<div>
<input v-model="msg">
<p>prop: {{ propMessage }}</p>
<p>msg: {{ msg }}</p>
<p>helloMsg: {{ helloMsg }}</p>
<p>computed msg: {{ computedMsg }}</p>
<Hello ref="helloComponent" />
<World />
<button @click="greet">Greet</button>
Clicked: {{ $store.state.count }} times, count is {{ evenOrOdd }}.
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementIfOdd">Increment if odd</button>
<button @click="incrementAsync">Increment async</button>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from '../lib/index'
import Hello from './Hello.vue'
import World from './World'
import { mapGetters, mapActions } from 'vuex'
// We declare the props separately
// to make props types inferable.
const AppProps = Vue.extend({
props: {
propMessage: String
}
})
@Component({
components: {
Hello,
World
},
// mapGetters & mapActions example
computed: mapGetters([
'evenOrOdd'
]),
methods: mapActions([
'increment',
'decrement',
'incrementAsync'
])
})
export default class App extends AppProps {
// inital data
msg: number = 123
// use prop values for initial data
helloMsg: string = 'Hello, ' + this.propMessage
// lifecycle hook
mounted () {
this.greet()
}
// computed
get computedMsg () {
return 'computed ' + this.msg
}
// method
greet () {
alert('greeting: ' + this.msg)
this.$refs.helloComponent.sayHello()
}
// direct dispatch example
incrementIfOdd() {
this.$store.dispatch('incrementIfOdd')
}
// dynamic component
$refs!: {
helloComponent: Hello
}
}
</script>
©
1.组件属性:首先采用Vue.extend创建一个组件类,在其中声明属性,最后的组件类只需要继承此组件类即可,属性可以直接在模板中绑定
2.子组件:使用装饰器@Component来配置子组件,注意子组件是对象形式
3.vuex:通过mapGetters合并store中的计算属性,通过mapActions合并store中的动作,这些都可以在@Component装饰器中完成,当然也可以使用mapState,mapMutation等方法
4.自定义数据:直接定义为类属性
5.生命周期方法:直接定义为相应名称类方法
6.普通方法:定义为类方法,不能与生命周期同名
7.计算属性,定义为getter方法,在方法内实现计算逻辑
8.引用:$refs,这个感叹号没看懂,
这里主要有一个问题,原有的Vue组件定义,使用Vue.extend就可以了,而使用ts开发时这部分内容存在于三个地方
1.extends:即组件类继承的父类,这个父类使用Vue.extend生成,其实这里除了props之外还可以定义其他属性
2.@Component:装饰器,上面在装饰器中定义了子组件,合并了store中的动作与计算属性
3.类属性:其实上面所有东西都可以在类中定义,但是ts编译检查中,this只能在类方法中访问,也只有定义在类上的属性,方法,可以通过this来访问
上面的官方示例基本上就是最佳使用方式了