npm init vite-app projectname
cd projectname
yarn
yarn dev
import { reactive } from 'vue'
const store = reactive({
state: {
message: 'helloworld'
},
setMessage(value) {
this.state.message = value
}
})
export default store
<template>
<h1>{{ store.state.message }}h1>
template>
<script>
import store from "../store/index";
export default {
setup() {
return {
store,
};
},
};
script>
import { reactive } from 'vue'
const store = reactive({
loveList: [],
setList(content) {
this.loveList = content
}
})
export default store
<template>
<h1>{{ store.loveList }}h1>
template>
<script>
import store from "./store/index";
export default {
setup() {
// 每日情话 api
let api = "https://api.uomg.com/api/rand.qinghua";
fetch(api)
.then((res) => res.json())
.then((result) => {
console.log(result);
store.setList(result.content);
});
return {
store,
};
},
};
script>
yarn add axios --save
<template>
<h1>{{ store.loveList }}h1>
template>
<script>
import store from "./store/index";
import axios from "axios";
export default {
setup() {
let api = "https://api.uomg.com/api/rand.qinghua";
axios.get(api).then((result) => store.setList(result.data.content));
return {
store,
};
},
};
script>
// 王者荣耀官网 找的一个url
let api = "https://pvp.qq.com/web201605/js/herolist.json";
根目录下新建vite.config.js
module.exports = {
proxy: {
'/api': {
target: "https://pvp.qq.com/",
changeOrigin: true, // 是否允许跨域
rewrite: path => path.replace(/^\/api/, '')
}
}
}
<template>
<ul v-for="(item, index) in store.loveList" :key="index">
<li>{{ item.cname }} - {{ item.title }}li>
ul>
template>
<script>
import store from "./store/index";
import axios from "axios";
export default {
setup() {
// 王者荣耀官网 找的一个url
let api = "/api/web201605/js/herolist.json";
// https://pvp.qq.com/web201605/js/herolist.json
axios.get(api).then((result) => store.setList(result.data));
return {
store,
};
},
};
script>
yarn add mockjs --save
文档链接
mock/index.js
import Mock from 'mockjs'
// 设置一下模拟返回数据的时间
Mock.setup({
timeout: '200-600'
})
Mock.mock(
"/user/userinfo",
"get",
() => {
return {
username: 'zhangsan',
className: '三年二班'
}
}
)
Mock.mock(
/\/account.*/,
"get",
(req, res) => {
console.log(req)
return {
info: '登录成功'
}
}
)
main.js
中引入
import './mock/index'
<template>
<h1>{{ store.loveList.username }}h1>
<h1>{{ store.loveList.className }}h1>
<p>info: {{ info }}p>
<p>infoC: {{ infoC }}p>
template>
<script>
import { ref } from "vue";
import store from "./store/index";
import axios from "axios";
export default {
setup() {
let infoC = ref("");
let api = "/user/userinfo";
axios.get(api).then(({ data }) => {
console.log(data);
store.setList(data);
});
let info = axios.get("/account?username=zhangsan").then((res) => {
console.log("res", res.data.info);
infoC.value = res.data.info;
return res.data.info; // 错误想法 以为会返回"登录成功" 其实axios 返回的是一个promise对象
});
return {
store,
info,
infoC,
};
},
};
script>
npm install -g @vue/cli
# OR
yarn global add @vue/cli
推荐使用vite 但也可以了解一下脚手架
不赘述 看文档即可
嗯,新建过程中出现了报错,之前使用脚手架创建项目都正常,突然报了一下错误
error An unexpected error occurred: "https://registry.yarnpkg.com/@vue%2fcli-plugin-babel: connect ETIMEDOUT 104.16.26.35:443".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
ERROR Error: command failed: yarn
Error: command failed: yarn
执行命令:yarn config set registry https://registry.npm.taobao.org -g
yarn config set registry https://registry.npm.taobao.org -g
》以下是命令执行后的提示:
》yarn config v1.22.18
》success Set "registry" to "https://registry.npm.taobao.org".
》Done in 0.06s.
store/index.js
import { createStore } from 'vuex'
export default createStore({
// 设置全局数据的地方
state: {
count: 0,
loveList: []
},
getters: {
totalPrice(state) {
return state.count * 100
}
},
// 修改状态的方法
mutations: {
// setCount(state) {
// state.count++
// },
setCountNum(state, num) {
state.count += num
},
setList(state, value) {
state.loveList = value
}
},
actions: {
getLove(context) {
let api = "https://api.uomg.com/api/rand.qinghua";
fetch(api)
.then((res) => res.json())
.then((result) => {
console.log(result);
context.commit('setList', result.content)
});
}
},
modules: {
}
})
<template>
<div class="home">
<h1>Home页面h1>
<h1>商品数量: {{ store.state.count }}h1>
<h1>商品价格:100h1>
<h1>总价: {{ store.getters.totalPrice }}h1>
<button @click="change">+1button>
<h1>情话h1>
<p>{{ store.state.loveList }}p>
div>
template>
<script>
// @ is an alias to /src
import { useStore } from "vuex";
import { onMounted } from "vue";
export default {
name: "HomeView",
setup() {
const store = useStore();
const change = () => {
store.commit("setCountNum", 10);
// store.commit("setCount");
};
onMounted(() => {
store.dispatch("getLove");
});
return {
change,
store,
};
},
};
script>
mapState mapGetters等方法 在setup中无法使用(达不到预期效果,看到好多人都是写了方法 都放在hooks目录下) 这里看到了一片博客
vue3.x实践经验-1、mapState、mapGetters、mapMutations、mapActions
<template>
<div class="home">
<h1>Home页面h1>
<h1>商品数量: {{ count }}h1>
<h1>商品价格:100h1>
<h1>总价: {{ totalPrice }}h1>
<button @click="change">+1button>
<h1>情话h1>
<p>{{ store.state.loveList }}p>
div>
template>
<script>
// @ is an alias to /src
import { useStore } from "vuex";
import { onMounted } from "vue";
import { toRef, toRefs } from "vue";
export default {
name: "HomeView",
setup() {
const store = useStore();
const change = () => {
store.commit("setCountNum", 10);
// store.commit("setCount");
};
// mapState
const { count, loveList } = toRefs(store.state);
// mapGetters
const totalPrice = toRef(store.getters, "totalPrice");
onMounted(() => {
store.dispatch("getLove");
});
return {
change,
store,
count,
totalPrice,
loveList,
};
},
};
script>
不是用setup 使用选项式API
<template>
<div class="home">
<h1>Home页面h1>
<h1>商品数量: {{ $store.state.count }}h1>
<h1>商品价格:100h1>
<h1>总价: {{ $store.getters.totalPrice }}h1>
<button @click="change">+1button>
<h1>情话h1>
<p>{{ $store.state.loveList }}p>
div>
template>
<script>
// @ is an alias to /src
// import { mapActions, mapGetters,mapState,mapMutations } from "vuex";
export default {
name: "HomeView",
methods: {
change() {
this.$store.commit("setCountNum", 10);
},
},
mounted() {
this.$store.dispatch("getLove");
},
};
script>
<template>
<div class="home">
<h1>Home页面h1>
<h1>商品数量: {{ count }}h1>
<h1>商品数量: {{ productCount }}h1>
<h1>商品价格:100h1>
<h1>总价: {{ totalPrice }}h1>
<button @click="change">+10button>
<button @click="setCountNum(5)">+5button>
<h1>情话h1>
<p>{{ loveList }}p>
div>
template>
<script>
// @ is an alias to /src
import { mapActions, mapGetters, mapState, mapMutations } from "vuex";
export default {
name: "HomeView",
methods: {
change() {
this.$store.commit("setCountNum", 10);
},
...mapMutations(["setCountNum"]),
...mapActions(["getLove"]),
},
computed: {
...mapState(["count", "loveList"]),
...mapState({
productCount: (state) => state.count,
}),
...mapGetters(["totalPrice"]),
},
mounted() {
// this.$store.dispatch("getLove");
this.getLove();
},
};
script>
Module
store/user.js
const user = {
state: () => ({
username: 'zhangsan',
age: 18
}),
mutations: {
setUserName(state) {
state.username = 'lisi'
},
// setAge(state) {
// state.age = 28
// },
setAge(state, value) {
state.age = value
}
},
actions: {
asyncSetAge(context) {
console.log(context)
setTimeout(() => {
// context.commit('setAge')
context.commit('setAge', 50)
}, 3000)
}
},
getters: {
description(state) {
return state.username + '的年龄是' + state.age + '岁'
}
}
}
export default user
store/index.js
import { createStore } from 'vuex'
import user from './user'
export default createStore({
modules: {
user
}
})
User.vue
<template>
<h1>User页面:用户名{{ $store.state.user.username }}h1>
<h1>User页面:年龄{{ $store.state.user.age }}h1>
<h1>User页面:描述{{ $store.getters.description }}h1>
<button @click="changeAge">异步修改年龄button>
template>
<script>
export default {
methods: {
changeAge() {
this.$store.dispatch("asyncSetAge");
},
},
};
script>