1.vue3中变量写法
import { reactive} from "vue";
export default {
setup() {
const state = reactive({
value: "",
ids: "",
bannerImg: "",
sightName: "",
gallaryImgs: [],
categoryList: []
});
//注意return出去
return { state};
}
}
//在template中的变量前面加state
<p class="sightName">{{state.sightName}}</p>
2.vue3变量省略state
//引入toRefs在return是...toRefs(state)就可以了
import { reactive,toRefs} from "vue";
export default {
setup() {
const state = reactive({
value: "",
ids: "",
bannerImg: "",
sightName: "",
gallaryImgs: [],
categoryList: []
});
return { ...toRefs(state)};
}
};
<p class="sightName">{{sightName}}</p>
3.vue3中不能用this
import { reactive,getCurrentInstance} from "vue";
export default {
setup() {
const state = reactive({
value: "",
ids: "",
bannerImg: "",
sightName: "",
gallaryImgs: [],
categoryList: []
});
//ctx就和vue2中this是一样的
const { ctx } = getCurrentInstance();
const go = () => {
ctx.$router.go("-1");
};
return { state, go};
}
};
4.vue3中事件
<p class="go" @click="go">
<van-icon name="arrow-left" />
</p>
import { reactive,getCurrentInstance} from "vue";
export default {
setup() {
const { ctx } = getCurrentInstance()
const go = () => {
ctx.$router.go("-1");
};
return { state, go};
}
}
5.vue3生命周期
import { reactive, onMounted} from "vue";
export default {
setup() {
onMounted(() => {
ctx.$axios.get("/mock/detail.json").then(res => {
console.log(res);
state.bannerImg = res.data.data.bannerImg;
state.gallaryImgs = res.data.data.gallaryImgs;
state.sightName = res.data.data.sightName;
state.categoryList = res.data.data.categoryList;
});
});
return { state, onMounted};
}
};
6.vue3安装axios
通过指令 npm install axios -S 安装axios和指令npm install vue-axios -S
安装vue-axios(注意:有时候我们在pack.json中看到vue-axios已经安装上去了,但是可能存在明明安装了,在组件中无法使用,因此需要重新安装vue-axios,这个在vue3.0中有80%的几率发生)
//在main.js全局配置axios
const app = createApp(App)
app.config.globalProperties.$axios = axios
6.vue3ref(注意这个ref和vue2中的ref不一样,千万别弄混了,vu3中的ref是给定的值创建一个响应式的数据对象。vue2中的ref是获取Dom元素
)
//自增
import {reactive, ref} from "vue";
export default {
name: "Home",
setup() {
const state = reactive({
value: "",
});
const count = ref(11111)
return { state,count };
}