项目创建
全局安装vite-app
npm i -g create-vite-app
创建项目
vue3test-project是项目名称
create-vite-app vue3test-project
代码编写
实例化vue
- 引用vue
import { reactive, toRefs, onMounted, computed, watch, watchEffect } from 'vue';
- 引用router
import { useRouter } from 'vue-router'
- 组件内写法
<template>
<div @click="test()">
1234567
</div>
</template>
<script>
import { reactive, toRefs, onMounted, computed, watch, watchEffect } from 'vue';
export default {
setup() {
const state = reactive({
// 这里写原来的data
});
onMounted(() => {});
function test() {
// 方法要return出去
}
return {
...toRefs(state),
test
};
}
};
</script>
<style lang="less" scoped>
</style>
- 取data
const state = reactive({
type: 1
});
console.log(state.type);
- 数据监听(两种方式)
watchEffect( () => {
console.log(state.type, '改变')
})
watch(() => state.type, (newValue, oldValue) => {
console.log(type, '改变')
})
- 父传子
父组件:
<template>
<test :type="type"/>
</template>
子组件:
export default {
name: 'test',
props: {
detail: {
type: Object,
default: {}
}
}
setup(props) {
console.log(props.type);
}
}
- 子传父
父组件:
<template>
<test @onjieshou="jieshou"/>
</template>
function jieshou(value) {
console.log(value); // value是1
}
子组件:
export default {
name: 'test',
emits: ['onjieshou'],
setup(props, { emit }) {
function test() {
emit('onjieshou', 1);
}
}
}