- 定义组件
import {defineComponent} from 'vue'
export default defineComponent({
name: '',
props: {
},
components: {},
//所有定义的数据,都在setup函数里
setup (props, ctx) {
return {
}
}
})
- ref定义单个数据
import {ref} from 'vue'
let num = ref(10)
let name = ref('jack')
let arr = ref(['a','b','c'])
setup (props, ctx) {
return {
num,
name
}
}
3.reactive定义对象类型的数据
import {reactive} from 'vue'
let data = reactive({
age: 10,
obj: {
price: 20
}
})
setup (props, ctx) {
return {
data
}
}
{{data.age}}
{{data.obj.price}}
import {reactive, toRefs} from 'vue'
let data = reactive({
age: 10,
obj: {
price: 20
}
})
setup (props, ctx) {
return {
...toRefs(data)
}
}
{{age}}
{{obj.price}}
- 方法的定义和使用
let clickNum = () => {
// 访问ref定义的数据,要写数据名.value
console.log(age.value)
// 访问reactive定义的,要写定义的数据名
console.log(data.age)
}
let clickData = (val) => {
console.log(val)
}
setup (props, ctx) {
return {
clickNum,
clickData
}
}
- 计算属性
import {computed} from 'vue'
let num = ref(10)
let addNum = computed(() => {
return num.value
})
setup (props, ctx) {
return {
addNum
}
}
- 状态管理
import {createStore} from 'vuex
export default createStore({
state: {
name: 'Jack',
},
mutations: {
changeName (state, payload) {
state.name = payload
}
},
actions: {
setName (store, params) {
store.commit('changeName', params)
}
}
})
import {useStore} from 'vuex'
setup (props, ctx) {
let store = useStore()
let list = computed(() => {
return store.state.list
})
return {
list
}
}
- 跳转路由
import {useRouter, useRoute} from 'vue-router'
setup (props, ctx) {
// 全局路由对象
let router= useRouter()
// 当前路由对象
let route = useRoute()
console.log(route.query)
let goTo = () => {
router.push({
path: '/about'
})
}
return {
goTo
}
}
- 组件生命周期
// 组件初始化
setup
//组件挂载的过程
onMounted
// 常用来发请求,做数据初始化的操作,接收路由传递的参数
onMounted(() => {
})
// 组件卸载时触发,清除定时器等
onUnmounted
onUnmounted(() => {})
网友评论