Vue3初体验(1)

1、Vite简单操作

安装

yarn global add [email protected]

创建项目

文档的命令

npm init vite-app 项目名
yarn create vite-app 项目名

等价于

全局安装后
cva 项目名
或
npx create-vite-app 项目名

2、Vue3与Vue2的区别

  • Vue3的Template支持多个跟标签,Vue2不支持
  • Vue3有createApp(),而Vue2是new Vue()
  • createApp(组件),new Vue({template,render})

3、Vue-router 4

3.1 查看所有版本号

npm info vue-router versions

3.2 安装vue-router 4

yarn add [email protected]

3.3 初始化vue-router

新建history对象

在main.ts中添加

import {createWebHashHistory, createRouter} from 'vue-router'

const history = createWebHashHistory()

新建router对象

const router = createRouter({
  history,
  routes: [
    {path: '/', component: Easyw},
  ],
});

app.use(router)

const app = createApp(App);
app.use(router);
app.mount('#app'); // 挂载组件

在App.vue中添加router-view


在routers中添加其他测试路由

routers: [{
    {path: '/', component: Easyw},
    {path: '/test', component: Test},
}]

在App.vue中添加router-link

  Easyw
  Test

3.4 添加子路由

const history = createWebHashHistory();
const router = createRouter({
  history,
  routes: [
    {path: '/', component: Home},
    {
      path: '/doc', component: Doc, children: [
        {path: 'switch', component: SwitchDemo},
        {path: 'switch', component: SwitchDemo},
      ],
    },
  ],
});

3.5 路由切换时进行操作

先导入你的router文件

import router from './router'
router.afterEach(() => {
  console.log(1);
});

4、provide和inject

4.1 实现思路

在最外层的页面中,定义provide变量。然后在子组件中使用inject可以及时拿到该变量。

4.2 使用步骤

在最外层声明
App.vue


子组件.vue


5、props外部传参

5.1 实现思路

在外部定义一个需要传参的属性名,后面带上需要传递的参数。在子组件中使用props接受该参数。如果需要修改使用context.event进行数据的修改。

5.2 使用步骤

外部组件

定义属性

setup(){
  const value = ref(true)
}

传递参数,并定义事件名

    

子组件

接受参数

props: {
  value: Boolean
}

修改参数

setup(props, context){
  const modify = () => {
    context.$emit('update:value', !props.value)
  }
}

5.3 使用v-model简化

删除外部事件名,使用v-model代替

    

注意:如果使用v-model,子组件内部的触发事件名必须为 update:外部定义的参数名

你可能感兴趣的:(Vue3初体验(1))