Skip to main content

常用使用

基础使用

安装

# 安装cli工具
yarn global add @vue/cli
# or
npm install -g @vue/cli

使用官方模板

npm init vite <project-name> -- --template vue | vue-ts
# or
yarn create vite <project-name> --template vue | vue-ts

已有项目下添加vue


获取DOM实例

通过ref属性获取对应的实例,实例初始化时需要赋值为null,建议在onMounted钩子后面再开始操作dom元素实例

<template>
<div class="icon-box" ref="menu_item"></div>
</template>
<script>
import { ref, onMounted, getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();

const menu_item = ref(null);
onMounted(()=>{
console.log(menu_item.value); // <div>这是根元素</div>
console.log(proxy.menu_item); // <div>这是根元素</div>
})
</script>

数据监听

官方文档

监听单个属性

const target = ref("")
const obj = reactive({target:""})

import { watch } from "vue";

// 仅监听单个属性
watch(target, (oldV,newV)=>{...})
watch(()=>obj.target, (oldV,newV)=>{...})

// 监听整个对象
watch(watch, (oldO,newO)=>{...})