美文网首页
Vue3 相对 Vue2 的区别(暂时记录)

Vue3 相对 Vue2 的区别(暂时记录)

作者: 弱冠而不立 | 来源:发表于2020-11-19 17:27 被阅读0次
  1. 合成式API取代选项型API
// vue2
export default {
  data() {
    return {
    };
  },
  created(){}
};
//vue3
export default {
    // 组件初始化构造的时候触发
    setup() {
        return;
    }
};
  1. 采用 反应API (reactivity API) 建立data
import { reactive } from "vue";
export default {
    setup() {
        const state = reactive({
            username: "",
            password: ""
        })
        return {
            state
        }
    }
};
  <div class="form">
    <h2>{{ state.title }}</h2>
    <input type="text" v-model="state.username" placeholder="Username" />
    <input type="text" v-model="state.password" placeholder="Password" />
    <button @click="login">Submit</button>
    <h4>Username: {{state.username}}</h4>
    <h4>Password: {{state.password}}</h4>
  </div>
  1. methods编写
    创建声名方法其实和声名数据状态是一样的。— 我们需要先声名一个方法然后在setup()方法中然后在return中返回, 这样我们的组件内就可以调用这个方法了
import { reactive } from "vue";
export default {
    setup() {
        const state = reactive({
            username: "",
            password: ""
        })
        const login = () => {
            console.log(state.username, state.password);
        }
        return {
            state,
            login
        }
    }
};
  1. 生命周期钩子
    在 Vue2,我们可以直接在组件属性中调用Vue的生命周期的钩子。但是在 Vue3 生周期钩子不是全局可调用的了,需要另外从vue中引入。和刚刚引入reactive一样,生命周期的挂载钩子叫onMounted。
import { reactive, onMounted } from "vue";
export default {
  setup() {
    const state = reactive({
      username: "",
      password: "",
    });
    const login = () => {
      console.log(state.username, state.password);
    };
    onMounted(() => {
      console.log("组件已挂载");
    });
    return {
      state,
      login,
    };
  },
};
  1. 计算属性
    在 Vue2 中实现,我们只需要在组件内的选项属性中添加即可。在 Vue3 使用计算属性,我们先需要在组件内引入computed。
    使用方式就和反应性数据(reactive data)一样,在state中加入一个计算属性
  setup() {
    const state = reactive({
      username: "",
      password: "",
      upperCaseUsername: computed(()=>state.username.toUpperCase())
    });
    return {
      state
    };
  },
  1. 数据监听方式由 Object.defineProperty(),改为ES6的Proxy

相关文章

网友评论

      本文标题:Vue3 相对 Vue2 的区别(暂时记录)

      本文链接:https://www.haomeiwen.com/subject/cgbjbktx.html