开始
- vue3发布没多久就迫不及待的写了个todolist 点击预览,当时也没有太多想法,只是感觉
composition api
比较新奇,仅此而已。
- 在不断使用中,也发现很多设计都是符合直觉,你觉得它应该这样它就是这样。简而言之好用!
- 之后看了一些关于vue3的分享,印象最深的其实是一张图
![截屏2022-06-06 上午9.11.14.png](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/9a4a6689337c47b08d11f172cdcce0b9~tplv-k3u1fbpfcp-zoom-in-crop-mark:1956:0:0:0.image?)
不要用2.x 的思维写3.x
- 很多时候不是写不出好代码,而是没有见过好代码。写代码的本质其实是模仿,没有见过有何谈模仿呢?
- 以下是一些很常见的例子
不要在 setup
定义一个 state
- 这里说的并不是不能定义一个
state
的变量,而是说不要定义一个用来存储所有数据的 state
,3.x 不需要一个 存储所有数据的 data
。为什么呢?
- 这个其实很简单,处理某项功能的逻辑应该写在一起。逻辑不会混在一起,变量也不应该混在一起。
<script>
import { reactive ,toRefs} from 'vue';
export default {
name: 'test',
setup() {
const state = reactive({
test1: '',
test2: {},
test3: [],
});
const testA = () => {
}
const testB = () => {
}
const testC = () => {
}
return {
...toRefs(state),
testA,
testB,
testC,
}
}
};
</script>
复制代码
<script>
import { reactive, ref } from 'vue';
export default {
name: 'test',
setup() {
const test1 = ref('');
const testA = () => {
test1.value = 'xxxx';
};
const test2 = reactive({ a: '1212' });
const testB = () => {
test2.a = 'xxxx';
};
const test3 = ref([]);
const testC = () => {
test3.value.push('121');
};
return {
test1,
testA,
testB,
testC
};
}
};
</script>
复制代码
- 不管如何去组织代码,目的都是易阅读、易维护为出发点。
不要把 getCurrentInstance
当成2.x的 this
来用
- getCurrentInstance 不是用来代替 2.x 的this的
![截屏2022-06-04 下午3.44.20.png](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ed740a3d0d384e47b33394bc0c4ddbcb~tplv-k3u1fbpfcp-zoom-in-crop-mark:1956:0:0:0.image?)
- 虽然官网文档已经做出的警告说明,但是很多人依然会如下这么写
![截屏2022-06-04 下午3.48.26.png](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7756362c94d044a783187a655e0025fa~tplv-k3u1fbpfcp-zoom-in-crop-mark:1956:0:0:0.image?)
<script>
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
export default {
name: 'test',
props: {
obj1: {
type: Object,
default: () => {
return {};
}
}
},
setup(props, { emit, slot }) {
const route = useRoute();
const router = useRouter();
const store = useStore();
const testObj = computed(() => store.state.testObj);
const a = props.obj1;
emit('xxxx', { a: 1 });
slot.default && slot.default();
return {
route,
router,
testObj
};
}
};
</script>
复制代码
关于学习vue3
- 如果会vue2 那么vue3上手难度并不算大,仔细读一遍官网跟着例子敲一敲,动手实践一下,基本上就算入门了。剩下的就是在不断的实践中进步了。
- 看视频 or 看文档,作者最初看了一些vue3的教学视频当然是看完文档后,最后收获并不算多大部分都是文档中的东西,不过是添加了一些自己的理解。这个每个人情况不同不能一概而论。
- 当你入门以后就可以看一些项目代码了,来实践了,没有项目怎么办?vue-devui 能收获多少就看自己了。
- 看完文档也有了一定的实践,那么就买一本 《vuejs设计与实现》来读。站内的一些关于vue3实现的文章其实就是书里的内容。
写在后边
- 上边这两个都是作者最初开始写的时候犯的错误,问题不大,但也是问题。
- 欢迎各位大佬友好留言交流。
往期文章