<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/vue3.js"></script>
</head>
<body>
<div id="counter">
<h1> counter:{{ num }}</h1>
</div>
<script>
// const Counter={
// data(){
// return{
// num:0
// }
// }
// }
const Counter={
data:function(){
return {
num:0
}
}
}
//创建一个应用,将配置的对象counter的内容渲染到选择器#counter的元素上
let app = Vue.createApp(Counter).mount("#counter")
console.log(app)
</script>
</body>
</html>
可以用 app.num = 10修改值
使用 npm:(在控制台终端输入)
npm init vite-app vue3demo03 //vue3demo03 项目名称
cd vue3demo03
npm install
npm run dev
最新创建步骤
# npm 6.x
$ npm init vite@latest --template vue
# npm 7+,需要加上额外的双短横线
$ npm init vite@latest -- --template vue
$ cd
$ npm install
$ npm run dev
创建好后生成:
App.vue
{{msg}}
运行结果:
改变输入框的值,上面的值就会改变,这就是双向绑定
单击后,会改变值
数据绑定最常见的形式就是使用“Mustache” (双大括号) 语法的文本插值:
<span>Message: {{ msg }}span>
Mustache 标签将会被替代为对应组件实例中 msg
property 的值。无论何时,绑定的组件实例上 msg
property 发生了改变,插值处的内容都会更新。
通过使用 v-once 指令,你也能执行一次性地插值,当数据改变时,插值处的内容不会更新。但请留心这会影响到该节点上的其它数据绑定:
<span v-once>这个将不会改变: {{ msg }}span>
{{msg}}
{{msg}}
{{msg}}
{{msg}}
{{content}}
展示结果:
点击helloword后:
{{msg}}
{{msg.split('')}}
{{ msg.split('').reverse() }}
{{msg.split('').reverse().join('')}}
{{color=='绿色'?'开心':'难过'}}
{{msg}}
展示结果:
{{msg.split('').reverse().join('')}}
{{reverseMsg}}
展示结果:
{{msg.split('').reverse().join('')}}
{{reverseMsg}}
{{msg}}
展示结果
hello
hello2
hello3
hello4
hello5
输出结果:
hello
hello2
hello3
hello4
展示效果
点击后
欢迎金主爸爸
欢迎会员登录
充值会让你更强大!
切换显示内容
展示结果:
我们可以使用 v-on
指令 (通常缩写为 **@**符号) 来监听 DOM 事件,并在触发事件时执行一些 JavaScript。用法为 v-on:click="methodName"
或使用快捷方式 @click="methodName"
{{num}}
{{num}}
{{num}}
{{num}}
{{num}}
{{num}}
{{num}}
展示结果
点击后
基础用法
你可以用 v-model 指令在表单 、
及
元素上创建双向数据绑定。它会根据控件类型自动选取正确的方法来更新元素。尽管有些神奇,但
v-model
本质上不过是语法糖。它负责监听用户的输入事件来更新数据,并在某种极端场景下进行一些特殊处理。
{{searchKey}}
{{lineText}}
[true,false]
{{checked}}
[喜欢,不喜欢]
{{checked1}}
苹果
雪梨
香蕉
{{fruits}}
man
woman
{{picked}}
{{city}}
{{cities}}
{{searchKey}}
{{searchKey}}
{{searchKey}}
展示结果:
这是头部组件
这是Footer组件
{{msg}} 这是Main组件
新闻内容是:{{content}}
从子组件获取到的值: {{msg}}
新闻内容是:{{content}}
父组件获取到的数据,传递给子组件: {{msg1}}
{{msg}}
展示结果:
点击后
计数: {{count}}
计数: {{num}}
展示结果
计数: {{count}}
计数: {{num}}
用户名: {{user.username}}
特点: {{user.type}}
用户名: {{username}}
特点: {{type}}
特点: {{type}}
特点 翻转: {{reverseType}}
展示结果:
点击后
username:{{username1}}
age:{{age}}
description:{{description}}
展示结果:
reactive和ref的细节问题
m1:{{m1}}
m2:{{m2}}
m3:{{m3}}
学生
name:{{name}}
classname:{{classname}}
展示结果
Hello App!
Go to Home
Go to About
<!--router/index.js-->
// 导入进来
// import VueRouter from 'vue-router'
import {createRouter,createWebHashHistory} from 'vue-router'
// 1. Define route components.
// These can be imported from other files
const Home = { template: 'Home' }
const About = { template: 'About' }
// 2. Define some routes
// Each route should map to a component.
// We'll talk about nested routes later.
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
]
// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = createRouter({
// 4. Provide the history implementation to use. We are using the hash history for simplicity here.
history: createWebHashHistory(),
routes, // short for `routes: routes`
})
//导出路由
export default router
<!--main.js-->
import { createApp } from 'vue'
import router from '../router'
import App from './App.vue'
import './index.css'
const app = createApp(App)
//使用路由
app.use(router)
app.mount('#app')
新闻页 {{$route.params.id}}
这是首页
404,找不到页面
<!--router/index.js-->
// 导入进来
// import VueRouter from 'vue-router'
import {createRouter,createWebHashHistory} from 'vue-router'
import Home from '../src/components/Home.vue'
import News from '../src/components/News.vue'
import NotFound from '../src/components/NotFound.vue'
// 1. Define route components.
// These can be imported from other files
//const Home = { template: 'Home' }
const About = { template: 'About' }
// 2. Define some routes
// Each route should map to a component.
// We'll talk about nested routes later.
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{
path:'/news/:id',
component:News
},
{
path:'/:path(.*)',
component:NotFound
}
]
// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = createRouter({
// 4. Provide the history implementation to use. We are using the hash history for simplicity here.
history: createWebHashHistory(),
routes, // short for `routes: routes`
})
//导出路由
export default router
/route/index.js
// 导入进来
// import VueRouter from 'vue-router'
import {createRouter,createWebHashHistory} from 'vue-router'
import Home from '../src/components/Home.vue'
import News from '../src/components/News.vue'
import NotFound from '../src/components/NotFound.vue'
import Article from '../src/components/Article.vue'
import Films from '../src/components/Films.vue'
// 1. Define route components.
// These can be imported from other files
//const Home = { template: 'Home' }
const About = { template: 'About' }
// 2. Define some routes
// Each route should map to a component.
// We'll talk about nested routes later.
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{
path:'/news/:id',
component:News
},
{
path:'/:path(.*)',
component:NotFound
},
{
path:'/article/:id(\\d+)',
component:Article
},
{
// id+ 是至少会有1个参数 例: /films/111/555
// id* 是可有可没有,也可以有任意多个 例:/films/ 或/films/111/555
// id? 是有,或者没有 ,不可以重复 例:/films/ 或/films/111
path:'/films/:id',
component:Films
}
]
// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = createRouter({
// 4. Provide the history implementation to use. We are using the hash history for simplicity here.
history: createWebHashHistory(),
routes, // short for `routes: routes`
})
//导出路由
export default router
Films.vue
Films页 {{$route.params.id}}
Article.vue
Article页: {{$route.params.id}}
展示结果
/route/index.js
// 导入进来
// import VueRouter from 'vue-router'
import {createRouter,createWebHashHistory, useRoute} from 'vue-router'
import Home from '../src/components/Home.vue'
import News from '../src/components/News.vue'
import NotFound from '../src/components/NotFound.vue'
import Article from '../src/components/Article.vue'
import Films from '../src/components/Films.vue'
import User from '../src/components/User.vue'
import Hengban from '../src/components/Hengban.vue'
import Shuban from '../src/components/Shuban.vue'
// 1. Define route components.
// These can be imported from other files
//const Home = { template: 'Home' }
const About = { template: 'About' }
// 2. Define some routes
// Each route should map to a component.
// We'll talk about nested routes later.
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{
path:'/news/:id',
component:News
},
{
path:'/:path(.*)',
component:NotFound
},
{
path:'/article/:id(\\d+)',
component:Article
},
{
// id+ 是至少会有1个参数 例: /films/111/555
// id* 是可有可没有,也可以有任意多个 例:/films/ 或/films/111/555
// id? 是有,或者没有 ,不可以重复 例:/films/ 或/films/111
path:'/films/:id+',
component:Films
},
{
// /user/:id 这样写的话 路径为 /user/11/hengban
// /user 这样写的话 路径为 /user/hengban
path:'/user/:id',
component:User,
children:[
{
path:'hengban',
component:Hengban
},
{
path:'shuban',
component:Shuban
}
]
}
]
// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = createRouter({
// 4. Provide the history implementation to use. We are using the hash history for simplicity here.
history: createWebHashHistory(),
routes, // short for `routes: routes`
})
//导出路由
export default router
User.vue 、 Hengban.vue 、 Shuban.vue
{{$route.params.id}}:user页面
这是横版页面
这是竖版页面
page.vue
这是page页面,学习编程导航
index.js
// 导入进来
// import VueRouter from 'vue-router'
import {createRouter,createWebHashHistory, useRoute} from 'vue-router'
import Home from '../src/components/Home.vue'
import News from '../src/components/News.vue'
import NotFound from '../src/components/NotFound.vue'
import Article from '../src/components/Article.vue'
import Films from '../src/components/Films.vue'
import User from '../src/components/User.vue'
import Hengban from '../src/components/Hengban.vue'
import Shuban from '../src/components/Shuban.vue'
import Page from '../src/components/Page.vue'
// 1. Define route components.
// These can be imported from other files
//const Home = { template: 'Home' }
const About = { template: 'About' }
// 2. Define some routes
// Each route should map to a component.
// We'll talk about nested routes later.
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{
name:"news",
path:'/news/:id',
component:News
},
{
path:'/:path(.*)',
component:NotFound
} ,
{
path:'/page',
component:Page
}
]
// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = createRouter({
// 4. Provide the history implementation to use. We are using the hash history for simplicity here.
history: createWebHashHistory(),
routes, // short for `routes: routes`
})
//导出路由
export default router
News.vue
新闻页 {{$route.params.id}}
展示结果:
<router-view name="ShopTop">router-view>
<router-view>router-view>
<router-view name="ShopFooter">router-view>
import ShopMain from '../src/components/ShopMain.vue'
import ShopTop from '../src/components/ShopTop.vue'
import ShopFooter from '../src/components/ShopFooter.vue'
const routes = [
{
path:'/shop',
components:{
default:ShopMain,
ShopTop:ShopTop,
ShopFooter:ShopFooter
}
}
]
展示结果
{
path:'/mail',
redirect:(to)=>{return {path:'/shop'}}
// redirect:"/shop"
}
{
path:'/shop',
alias:"/jihushop",
//alias:["/q11","/222"],
components:{
default:ShopMain,
ShopTop:ShopTop,
ShopFooter:ShopFooter
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4eiiJbUB-1649577549486)(https://gitee.com/yin-jihu/images/raw/master/blog/20220316215229.png)]
replace : 使覆盖原来的页面,让其不能往回退
page.vue
这是page页面,学习编程导航
//前进
//后退
路由守卫就是 和权限差不多 没有权限进不去该页面
{
path:'/page',
component:Page,
beforeEnter:(to,from)=>{
console.log('beforeEnter')
}
},
router.beforeEach((to, from,next) => {
// ...
// explicitly return false to cancel the navigation
console.log(to)
next()
//return false
})
page.vue
展示结果
App.vue
Helloworld.vue
{{ store.state.message }}
store/index.js
import {reactive} from 'vue'
const store={
state:reactive({
message:"helloworld"
}),
setMessage(value){
this.state.message = value;
}
}
//导出默认值
export default store;
使用axios实现前后端交互时需要先安装axios:
npm install axios --save
App.vue
ajax请求
{{i}}{{item.text}}
components/HelloWorld.vue
{{ store.state.message }}
store/index.js
import {reactive} from 'vue'
const store={
state:reactive({
message:"helloworld",
duanziList:[]
}),
setMessage(value){
this.state.message = value;
},
setDzList(list){
this.state.duanziList = list
}
}
//导出默认值
export default store;
展示结果
在项目的根目录下创建一个vite.config.js配置文件
vite.config.js
module.exports = {
proxy:{
'/api':{
target:'https://pvp.qq.com/',
changeOrigin:true,//是否允许跨域
rewrite:path => path.replace(/^\/api/, '')
}
}
}
App.vue
ajax请求
{{item.cname}}===>{{item.title}}
store/index.js
import {reactive} from 'vue'
const store={
state:reactive({
message:"helloworld",
duanziList:[]
}),
setMessage(value){
this.state.message = value;
},
setDzList(list){
this.state.duanziList = list
}
}
//导出默认值
export default store;
展示结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5MnF7QwH-1649577549492)(https://gitee.com/yin-jihu/images/raw/master/blog/20220317102426.png)]
mockjs 官网:http://mockjs.com/
# 安装
npm install mockjs --save
// 使用 Mock
var Mock = require('mockjs')
var data = Mock.mock({
// 属性 list 的值是一个数组,其中含有 1 到 10 个元素
'list|1-10': [{
// 属性 id 是一个自增数,起始值为 1,每次增 1
'id|+1': 1
}]
})
// 输出结果
console.log(JSON.stringify(data, null, 4))
例子
App.vue
ajax请求
{{item.cname}}===>{{item.title}}
{{store.state.message}}
/mock/index.js
//导入mock
import Mock from 'mockjs'
//设置一下模拟返回数据的时间
Mock.setup({
timeout:'200-600'
})
Mock.mock(
//请求的路径
"/user/userinfo",
'get',
(req)=>{
console.log(req)
return{
username:"老马",
type:'帅!'
}
}
)
Mock.mock(
//请求的路径
/\/account.*/, //正则匹配 .* :匹配 account后面所有的
'get',
(req)=>{
console.log(req)
return{
info:"登录成功"
}
}
)
main.js
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import './mock/index.js' //要是与后端发送请求只需把这句话注释掉
createApp(App).mount('#app')
目录结果
输出结果:
npm install -g @vue/cli
//查看版本
vue --version
安装时出现的问题:
VSCode的终端输入vue --version
报错:vue : 无法加载文件 D:\nodejs\node_global\vue.ps1,因为在此系统上禁止运行脚本。
解决办法
(1)以管理员身份运行VSCode
(2)执行命令:get-ExecutionPolicy(取得shell的当前执行策略)
显示Restricted(表示状态是禁止的)
(3)执行命令:set-ExecutionPolicy RemoteSigned
(4)执行命令:get-ExecutionPolicy,显示RemoteSigned
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-egFHiasX-1649577549502)(https://gitee.com/yin-jihu/images/raw/master/blog/20220317115040.png)]
创建项目命令:
vue create vueproject01
#安装 element Ui
npm i element-ui -S #vue2.0版本
npm install element-plus --save
vue add element
vue add element-plus #vue3.0使用这个安装 element Ui 插件
npm install [email protected] --save #安装echarts插件
npm i echarts -S
在main.js中引入
import echarts from 'echarts'
Vue.prototype.$echarts = echarts
第一步,创建项目结构,第一个是vue3,第二个是vue2,第三个是自定义,我们选择第三个自定义结构,回车。
第二步,选择模块,上下选择,选中按空格,选好后按回车 。选择四个就可以了(linter 以后再选,效验用的)
**第三步:**需要进行的一些配置
第四步:等待创建好(此时必须网好才行)
第五步:运行项目
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cVyYcoaF-1649577549526)(https://gitee.com/yin-jihu/images/raw/master/blog/20220317152117.png)]
HomeView.vue
商品数量:{{$store.state.count}}
商品价格:100
商品总价: {{$store.getters.totalPrice}}
段子
{{item.text}}
/store/index.js
import { createStore } from 'vuex'
export default createStore({
//设置全局数据的地方
state: {
count:1,
dzList:[]
},
getters: {
totalPrice:function(state){
return state.count*100
}
},
//修改状态的方法 (同步的操作)
mutations: {
setCount:function(state){
state.count++;
},
setCountNum:function(state,num){
state.count+=num;
},
setDzList:function(state,arr){
state.dzList =arr;
}
},
//异步的操作 (比如 ajax)
actions: {
getDz:function(context){
var api = "https://api.apiopen.top/getJoke?page=1&count=10&type=text"
fetch(api).then(res=>res.json()).then(result=>{
console.log(result);
context.commit('setDzList',result.result);
})
}
},
modules: {
}
})
展示效果:
此映射方法让其 不用写($store.state.count)这么长的名字了
HomeView.vue
商品数量:{{$store.state.count}}
商品数量:{{count}}
商品数量:{{productCount}}
商品价格:100
商品总价: {{$store.getters.totalPrice}}
商品总价: {{totalPrice}}
段子
{{item.text}}
/store/index.js
import { createStore } from 'vuex'
export default createStore({
//设置全局数据的地方
state: {
count:1,
dzList:[]
},
getters: {
totalPrice:function(state){
return state.count*100
}
},
//修改状态的方法 (同步的操作)
mutations: {
setCount:function(state){
state.count++;
},
setCountNum:function(state,num){
state.count+=num;
},
setDzList:function(state,arr){
state.dzList =arr;
}
},
//异步的操作 (比如 ajax)
actions: {
getDz:function(context){
var api = "https://api.apiopen.top/getJoke?page=1&count=10&type=text"
fetch(api).then(res=>res.json()).then(result=>{
console.log(result);
context.commit('setDzList',result.result);
})
}
},
modules: {
}
})
展示效果
store/user.js
const user = {
state:() =>({
username:'老马',
age:27
}),
mutations:{
setUsername:function(state){
state.username = '小陈'
},
setAge:function(state,value){
state.age = value
}
},
actions:{
asyncSetAge:function(context){
console.log(context)
setTimeout(()=>{
context.commit('setAge',50);
},3000);
}
},
getters:{
description:function(state,getters,rootState){
return state.username +'的年龄是'+ state.age + '岁'
}
}
}
export default user
/views/User.vue
用户名:{{$store.state.user.username}}
年龄:{{$store.state.user.age}}
描述:{{$store.getters.description}}
store/index.js
import { createStore } from 'vuex'
import user from './user'
export default createStore({
//设置全局数据的地方
state: {
count:1,
dzList:[]
},
getters: {
totalPrice:function(state){
return state.count*100
}
},
//修改状态的方法 (同步的操作)
mutations: {
setCount:function(state){
state.count++;
},
setCountNum:function(state,num){
state.count+=num;
},
setDzList:function(state,arr){
state.dzList =arr;
}
},
//异步的操作 (比如 ajax)
actions: {
getDz:function(context){
var api = "https://api.apiopen.top/getJoke?page=1&count=10&type=text"
fetch(api).then(res=>res.json()).then(result=>{
console.log(result);
context.commit('setDzList',result.result);
})
}
},
modules: {
user
}
})
router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import User from '../views/User.vue'
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
},
{
path: '/user',
name: 'User',
component: User
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
默认情况下,模块内部的 action 和 mutation 仍然是注册在全局命名空间的——这样使得多个模块能够对同一个 action 或 mutation 作出响应。Getter 同样也默认注册在全局命名空间,但是目前这并非出于功能上的目的(仅仅是维持现状来避免非兼容性变更)。必须注意,不要在不同的、无命名空间的模块中定义两个相同的 getter 从而导致错误。
如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true
的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。
User.vue
用户名:{{$store.state.user.username}}
年龄:{{$store.state.user.age}}
描述:{{$store.getters.description}}
用户名:{{$store.state.user1.username}}
年龄:{{$store.state.user1.age}}
描述:{{$store.getters['user1/description']}}
用户名:{{user1.username}}
年龄:{{user1.age}}
描述: {{description}}
store/user1.js
const user = {
namespaced:true,
state:() =>({
username:'隔壁老王',
age:46
}),
mutations:{
setUsername:function(state){
state.username = '小王'
},
setAge:function(state,value){
state.age = value
}
},
actions:{
asyncSetAge:function(context,value){
console.log(context)
setTimeout(()=>{
context.commit('setAge',value);
},1000);
}
},
getters:{
description:function(state,getters,rootState){
return state.username +'的年龄是'+ state.age + '岁'
}
}
}
export default user
展示效果:
#安装 element Ui
npm i element-ui -S #vue2.0版本
npm install element-plus --save
vue add element
vue add element-plus #vue3.0使用这个安装 element Ui 插件
#安装echarts
npm install [email protected] --save #安装echarts插件
npm i echarts -S
在main.js中引入
import echarts from 'echarts' #v4版本这样引用echarts
Vue.prototype.$echarts = echarts
import * as echarts from 'echarts' #v5版本这样引用echarts
#安装axios
npm install axios --save
import axios from 'axios'
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wWu9mKd3-1649577549539)(https://gitee.com/yin-jihu/images/raw/master/blog/20220328093337.png)]