Vue3.0+vueX+router创建到使用

创建项目

创建vue3.0最方便的两种方式。

  1. 控制台输入vue ui 可视化创建项目是我常用的方式直接可视化创建配置依赖。
  2. 使用vite工具创建项目,具体步骤如下:

vite优点详细说明

[https://www.zhihu.com/question/394062839/answer/1496127786]

全局安装vite

npm i -g create-vite-app

创建vite项目

create-vite-app vue3-demo

运行vite项目

npm i
npm run dev

vue3.0 新特性体验 直接上代码

<!--
 * @FilePath: \vue3-test\src\components\HelloWorld.vue
-->
<template>
  <div class="div">
    <router-link :to="{ name: 'User', params: { userId: 123 }}"><div>user</div></router-link>
    <h2>home</h2>
    <h3>{{count}}</h3>
    <p>{{state.count}}</p>
    <button @click="add()">按钮</button>
  </div>
</template>

<script>
import {ref,onMounted,reactive, onUpdated, onUnmounted, nextTick} from 'vue'
export default {
  name: 'Home',
  setup(){
    const count = ref(90)
    const state = reactive({
      count: 0,
      str: 'hello'
    })
    onMounted(() =>{
      console.log("加载完成");
      add()
    })
    onUpdated(() =>{
      console.log("更新完毕");
    })
    onUnmounted(() =>{
      console.log("已销毁");
    })
    // 在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
    nextTick( () => {
      console.log('获取更新后的 DOM。');
    })
    /*注意观察reactive与ref的区别
    reactive 是接收一个普通对象,返回该对象的响应式代理
    ref 也是接收一个参数并返回一个响应式且可改变的 ref 对象,一般参数是基础类型,比如数值或字符
    串等。如果传入的参数是一个对象,将会调用 reactive 方法进行深层响应转换。ref 对象拥有一个指向内
    部值的单一属性 .value,即当你要访问它的值时,需要 .value 拿到它的值。但是如果是在 setup 中返回
    且用到模板中时,在 {{}} 里不需要加 .value 访问,在返回时已经自动解套。
    */
    const add = () => {
       count.value += 1
       state.count++
    }
    return {
      count,
      add
    }
  }
}
</script>
<style scoped>
 
</style>

VueX使用

import { createStore } from 'vuex'

export default createStore({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

routerd使用

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

main.js中引入

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

createApp(App).use(store).use(router).mount('#app')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值