vue3升级差异体验
- 0
#讨论区
00条评论
实时对话
loading...
<script setup>
实验性<style vars>
实验性<style scoped>
现在可以包含全局规则或只针对插槽内容的规则vue2 选项式api
vue3基本模板
html
setup
入口函数 在beforeCreate
之后created
之前执行
接收props和context={slots,emit,refs}
js
setup的props不能直接解构,否则会失去响应式,
如果要解构,可以使用
toRefs
js
js
js
reactive
和ref
js
js
js
js
<template>
<button @click="increment">
Count is: {{ state.count }}, double is: {{ state.double }}
</button>
</template>
<script>
import { reactive, computed, defineComponent, onMounted } from 'vue';
export default defineComponent({
props:{
msg:{type:String}
},
setup() {
const
const state = reactive({
count: 0,
double: computed(() => state.count * 2),
});
function increment() {
state.count++;
}
onMounted(() => {
console.log('component is mounted!');
});
return {
state,
increment,
};
},
});
</script>
export default {
components: { RepositoriesFilters, RepositoriesSortBy, RepositoriesList },
props: {
user: { type: String }
},
setup(props,context) {
console.log(props) // { user: '' }
return {} // 这里返回的任何内容都可以用于组件的其余部分
}
// 组件的“其余部分”
}
import { toRefs } from 'vue'
setup(props) {
const { title } = toRefs(props)
console.log(title.value)
console.log(props.value)
}
export default {
setup(props) {
/* ✗ BAD */
const { count } = props
watch(() => {
/* ✓ GOOD */
const { count } = props
console.log(count)
})
return () => {
/* ✓ GOOD */
const { count } = props
return h('div', count)
}
}
}
export default {
/* ✗ BAD */
setup({ count }) {
watch(() => {
console.log(count) // not going to detect changes
})
return () => {
return h('div', count) // not going to update
}
}
}
import { reactive } from 'vue'
// reactive state
const state = reactive({
count: 0
})
//类似于vue2的`Vue.observable()`
import { ref } from 'vue'
const counter = ref(0)
console.log(counter) // { value: 0 }
console.log(counter.value) // 0
counter.value++
console.log(counter.value) // 1
//获取鼠标位置hooks
import { ref, onMounted, onUnmounted } from 'vue'
export function useMousePosition() {
const x = ref(0)
const y = ref(0)
function update(e) {
x.value = e.pageX
y.value = e.pageY
}
onMounted(() => {
window.addEventListener('mousemove', update)
})
onUnmounted(() => {
window.removeEventListener('mousemove', update)
})
return { x, y }
}
//组件使用
import { useMousePosition } from './mouse'
export default {
setup() {
const { x, y } = useMousePosition()
// other logic...
return { x, y }
}
}