Vue 3.0初体验,学习笔记
起手式
- 安装vue-cli
npm install -g @vue/cli
- 创建项目
npm create 项目名
创建项目时选择 Manually select features ,在选择项目时勾选vue 3.0选项
基础使用
父组件
<template>
<div class="about">
<h1>接收子组件的值:{{childValue}}</h1>
<vueCom :childValue="parentValue" @changeValue='changeValue'></vueCom>
</div>
</template>
<script>
import vueCom from '../components/Vue3Com.vue'
import { ref } from 'vue'
export default {
components: {
vueCom
},
setup() {
let parentValue = ref('父组件的值')
let childValue = ref()
let changeValue = (val) => {
childValue.value = val
}
return {
parentValue,
childValue,
changeValue
}
}
}
</script>
<style lang="less" scoped>
h1 {
color: red
}
</style>
子组件
<template>
<div class="vue3Test">
<div class="textValue">
<h1>vuex存储的值:{{storeValue}}</h1>
<h1>count:{{count}}</h1>
<h1>接收父组件的值:{{parentValue}}</h1>
<button @click="add" style="margin-right:40px">count++</button>
<button @click="changeValue">change child value</button>
</div>
</div>
</template>
<script>
import { useStore } from 'vuex'
import { computed, ref, watch } from 'vue'
export default {
// 父组件传值
props: {
childValue: {
type: String,
default: null
}
},
// 一个组件选项,在组件被创建之前,props 被解析之后执行。组合式 API 的入口
setup(props, context) {
// vue 3.0中vuex的使用
let store = useStore()
let storeValue = computed(() => store.state.user)
// 使用父组件的值
let parentValue = ref(0)
let changeValue = () => {
parentValue.value = props.childValue
context.emit('changeValue', '我是子组件的值')
}
// 监听变化
let count = ref(0)
let add = () => {
count.value++
}
watch(count, (newValue, preValue) => {
console.log('count发生了变化', newValue, preValue)
})
return {
storeValue,
count,
parentValue,
changeValue,
add
}
}
}
</script>
<style lang='less' scoped>
h1 {
color: red
}
</style>