初窥vue3.0

  vue3.0也出来了很久一段时间了。每次看新闻逛论坛好多都是关于vue3.0的,今天抽空也学习了下,由于是第一次接触,因此查过不少资料,踩过不少坑。特此记录下。

  (1)、全局安装最新版本的 @vue/cli npm install -g @vue/cli@next 

  (2)、使用vite(是一个 web 开发构建工具,由于其原生 ES 模块导入方法,它允许快速提供代码)来快速创建一个vue项目 npm init vite-app <project-name> ,这时候可能报如下错误:

  

 

  百思不得其解,查资料没查到,想到了很久没有更新node版本,当即去更新了下node版本,然后重新执行如上命令后创建成功了。接下来依次执行如下命令:

cd <project-name>
npm install
npm run dev

  好了,项目终于跑起来了。一个很简单的项目,里面就一个helloworld文件,打开一看,wtf,什么鬼?怎么还是vue2的语法。基本的vue-router也没有包含进去。

  好吧,自己动手慢慢搭建吧。首先创建一个hello.vue文件,里面内容如下:

<template>
  <div class="wrapper">
    hello{{name}}
    <h4 @click="test">hello world!</h4>
  </div>
</template>

<script>
import { reactive, toRefs, onUpdated, onMounted } from "vue";
import { useRouter } from "vue-router";

export default {
  setup() {
    const router = useRouter();
    
    // 响应式数据
    const state = reactive({
      name: "boyjiang"
    });
    // 页面事件函数
    const test = () =>{
      state.name = state.name == "江男孩" ? 'boyyang' : '江男孩'
      router.push("/helloWorld");
    }

    onMounted(() => {
      console.log('mounted', state.name)
    })
    onUpdated(() => {
      console.log("onUpdated", state.name)
    })
    
    // 将数据以及函数return 出去,不然外面是无法访问到数据和事件的
    return {
      ...toRefs(state),
      test
    }
  }
};
</script>

  这就完了吗?no,no,no。还得安装vue-router并创建路由文件,否则,项目运行起来是会报错的。

  使用命令来安装vue-router: npm install vue-router@next 

  安装完后在项目的src文件夹下创建router文件夹,然后在该文件夹里创建路由route.js文件,内容如下:

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

const routerHistory = createWebHistory()

const router = createRouter({
  history: routerHistory,
  routes: [
    {
      path: '/hello',
      component: () => import (/* webpackChunkName: 'Hello' */ '../components/hello.vue')
    },
    {
      path: '/helloWorld',
      component: () => import (/* webpackChunkName: 'HelloWorld' */ '../components/HelloWorld.vue')
    }
  ]
})

export default router

 路由跳转方式:

  (1)、

import { useRouter } from 'vue-router';
export default {
  setup() {
    const router = useRouter();
     router.push("/about");
    return{}
  }
}

  (2)、

<script>
import { reactive, toRefs, onUpdated, onMounted, getCurrentInstance } from "vue";


export default {
  setup() {
   const { ctx } = getCurrentInstance()
    ctx.$router.push("/helloWorld")

    onMounted(() => {)
    onUpdated(() => {})
    
  
    return {
        // return数据或方法
    }
  }
};
</script>

 

 

 修改app.vue文件中的代码如下:

<template>
  <div id="app" :style="{'min-height':height + 'px'}">
      <div class="hei">{{height}}</div>
      <router-view />
  </div>
</template>

<script>
import { ref, reactive, toRefs, onMounted} from "vue";
export default {
  name: 'App',
  setup() {
      let state = reactive({
          height: window.innerHeight
      })
      const resize = () => {
          state.height = window.innerHeight
      }
      
      onMounted(() => {
          state.height = window.innerHeight
          window.addEventListener('resize', resize)
      })
      return {
          ...toRefs(state)
      }
  }
}
</script>

  这样,一个简易的项目就搭起来了。。访问hello文件,里面创建了一个响应式变量,通过点击事件可改变该变量的值,同时会跳转到helloworld文件。

 

 

   下面来说一下里面用到的一些新特性:

  (1)、setup:是专门为使用vue3的composition-api新特性开放的统一入口,执行时机位于beforeCreate之前。

  (2)、reactive:可以创建多个响应式的数据对象,如const state = reactive({name: "boyjiang"})。

  (3)、ref:根据给定的值,创建响应式的数据对象,返回值是一个对象,且只有value,如:const a = ref(0)。

  (4)、toRefs:该函数能将reactive创建的响应式对象,转化成为普通的对象,只不过,这个对象上的每个节点,都是ref()类型的响应式数据。

  vue3.0生命周期钩子如下:

  

 

  watch:

  (1)、引入watch,例如

<template>
    <div class="wrapper">
        这是一个测试页面
        <p>姓名{{name}}</p>
        <p>年龄{{age}}</p>
        <p @click="change">change</p>
    </div>
</template>

<script>
    import {toRefs, reactive, watch} from 'vue'
    export default {
        setup () {
            const state = reactive({
                name: 'tom',
                age: 35
            })
            // 监听多个源
            watch([() => state.name, () => state.age], ([name, age], [prevName, prevAge]) => {
                console.log('watch-name', name)
                console.log('watch-prevName', prevName)
                console.log('watch-age', age)
                console.log('watch-prevAge', prevAge)
            })
            // 监听单一源
            // watch(() => state.name, (name, prevName) => {
            //     console.log('watch-name', name)
            //     console.log('watch-prevName', prevName)
            // })
            const change = () => {
                state.name = state.name == 'tom' ? 'john' : 'tom'
                state.age ++
            }
            return {
                ...toRefs(state),
                change
            }
        }
    }
</script>

 

  computed用法:

  

 

posted @ 2020-09-22 15:50  江峰★  阅读(319)  评论(0编辑  收藏  举报