vue3.0快速上手

仓库地址:GitHub
文档地址:连接

@vue/composition-api

vue3.0为了更好的类型推断,(避免使用装饰器),完全使用普通函数,用TS重写了源码,所以在如果你使用Vue3.0开发,最好和TS搭配使用。

数据通信之前使用高阶组件(会导致没有更新的组件也进行重新渲染),mixin(变量名会和组件内部冲突),作用域插槽(会导致数据来源不明确)

@vue/composition-api使用更加简单,没有分散的去使用methods和computed,而是组合是API

快速上手

把Vue的源码包下载下来,地址链接

git clone https://github.com/vuejs/vue-next.git

然后开发环境打包,为什么打包,因为源码是TS写的,我们要打包成JS文件

npm run dev

然后package里面有个dist文件里面就是打包的内容,在这个目录建个HTML文件然后把JS引入到页面中就可以使用了

代码示例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="container"></div>

  <script src="vue.global.js"></script>

  <script>

    // 我们获取鼠标的位置,在很多地方被使用
    function usePosition () {
      let position = Vue.reactive({x: 0, y: 0})
      function update (e) {
        pos.x = e.pageX
        pos.y = e.pageY
      }
      // 函数里面使用生命周期
      Vue.onMounted(() => {
        window.addEventListener('mousemove', update)
      })
      Vue.onUnmounted(() => {
        window.removeEventListener('mousemove', update)
      })
      return position
    }


    const App = {
      // 启动函数
      setup () {
        let state = Vue.reactive({name: 'hello world'})
        let position = usePosition() // 这里调用了生命周期属于这个组件了
        // 返回的对象会作为渲染的上下文
        return {
          state,
          change,
          position
        }
        function change () {
          // 这是普通函数,之前的this定死了都是实例,现在的不是了
          state.name = '前端精髓'
        }
      },
      template: `
{{state.name}}
`
} Vue.createApp().mount(App, container) </script> </body> </html>

你可能感兴趣的:(vue)