以下是我自己总结的部分vue3写法,用于日常项目的开发,主要是双向数据绑定,钩子函数,组件通信,vux,vue-router等用法
<div>
<p>vue3 部分示例</p>
<a-input v-model:value="inputVal" />
</div>
</template>
<script setup>
import {
ref,
reactive,
onMounted,
unmounted,
computed,
watch,
defineProps,
defineEmits,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
// props
const props = defineProps({
visible: {
type: Boolean,
default: false,
},
});
// emit
const emit = defineEmits(["close", "success"]);
emit("close");
emit("success");
// store vux
const store = useStore();
// 取值
store.state.count;
//commit提交
const myCommit = () => {
store.commit("commitValue");
};
const user = computed(() => {
return store.state.user;
});
// ref 和 reactive 都是用来绑定响应式数据
// 例如 ref html里面使用ref定义的对象直接用 {{inputVal}} script里面使用 inputVal.value
const inputVal = ref(null); // ref() 括号里面可以设置初始值
// 例如 reactive html里面使用reactive定义的对象直接用 {{state.reactiveVal}} script里面使用 state.reactiveVal
const state = reactive({
name: "vue",
age: 16,
reactiveVal: "",
});
// 钩子 onMounted 类似vue2 的
onMounted(() => {
// to do
});
unmounted(() => {});
// watch computed
const nextAge = computed(() => {
return state.age + 1;
});
watch(
() => props.visible,
(newVal, oldVal) => {
// to do
},
{
immediate: true,
deep: true,
}
);
// 使用路由 router route
const router = useRouter();
const route = useRoute();
// 此时和vue2 里面使用的方法一样
//
</script>
<style></style>