vue

vue

1.订单列表实例

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Vue.js 订单表单</title>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <style>
    /*  隐藏未编译的变量 */

    [v-cloak] {
      display: none;
    }

    *{
    	margin:0;
    	padding:0;
    }

    body{
    	font:15px/1.3 'Open Sans', sans-serif;
    	color: #5e5b64;
    	text-align:center;
    }

    a, a:visited {
    	outline:none;
    	color:#389dc1;
    }

    a:hover{
    	text-decoration:none;
    }

    section, footer, header, aside, nav{
    	display: block;
    }

    /*-------------------------
    	订单表单
    --------------------------*/

    form{
    	background-color: #61a1bc;
    	border-radius: 2px;
    	box-shadow: 0 1px 1px #ccc;
    	width: 400px;
    	padding: 35px 60px;
    	margin: 50px auto;
    }

    form h1{
    	color:#fff;
    	font-size:64px;
    	font-family:'Cookie', cursive;
    	font-weight: normal;
    	line-height:1;
    	text-shadow:0 3px 0 rgba(0,0,0,0.1);
    }

    form ul{
    	list-style:none;
    	color:#fff;
    	font-size:20px;
    	font-weight:bold;
    	text-align: left;
    	margin:20px 0 15px;
    }

    form ul li{
    	padding:20px 30px;
    	background-color:#e35885;
    	margin-bottom:8px;
    	box-shadow:0 1px 1px rgba(0,0,0,0.1);
    	cursor:pointer;
    }

    form ul li span{
    	float:right;
    }

    form ul li.active{
    	background-color:#8ec16d;
    }

    div.total{
    	border-top:1px solid rgba(255,255,255,0.5);
    	padding:15px 30px;
    	font-size:20px;
    	font-weight:bold;
    	text-align: left;
    	color:#fff;
    }

    div.total span{
    	float:right;
    }
    </style>

</head>
<body>

<!-- v-cloak 隐藏未编译的变量,直到 Vue 实例准备就绪。 -->

<form id="main" v-cloak>

	<h1>Services</h1>

	<ul>

		<!-- 循环输出 services 数组, 设置选项点击后的样式 -->

		<li v-for="service in services" v-on:click="toggleActive(service)" v-bind:class="{ 'active': service.active}">

			<!-- 显示订单中的服务名,价格
                 Vue.js 定义了货币过滤器,用于格式化价格 -->

			{{service.name}} <span>{{service.price | currency}}</span>

		</li>
	</ul>

	<div class="total">

		<!-- 计算所有服务的价格,并格式化货币 -->

		Total: <span>{{total() | currency}}</span>
        
	</div>

</form>
<script>

// 自定义过滤器 "currency". 
Vue.filter('currency', function (value) {
    return '$' + value.toFixed(2);
});

var demo = new Vue({
    el: '#main',
    data: {
    	// 定义模型属性 the model properties. The view will loop
        // 视图将循环输出数组的数据
        services: [
        	{
        		name: 'Web Development',
        		price: 300,
        		active:true
        	},{
        		name: 'Design',
        		price: 400,
        		active:false
        	},{
        		name: 'Integration',
        		price: 250,
        		active:false
        	},{
        		name: 'Training',
        		price: 220,
        		active:false
        	}
        ]
    },
    methods: {
    	toggleActive: function(s){
            s.active = !s.active;
    	},
    	total: function(){

        	var total = 0;

        	this.services.forEach(function(s){
        		if (s.active){
        			total+= s.price;
        		}
        	});

    	   return total;
        }
    }
});
	
</script>
</body>
</html>

2.搜索页面实例

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Vue.js 搜索页面</title>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    
    <style>
    /* 隐藏未编译的变量 */

    [v-cloak] {
      display: none;
    }

    *{
        margin:0;
        padding:0;
    }

    body{
        font:15px/1.3 'Open Sans', sans-serif;
        color: #5e5b64;
        text-align:center;
    }

    a, a:visited {
        outline:none;
        color:#389dc1;
    }

    a:hover{
        text-decoration:none;
    }

    section, footer, header, aside, nav{
        display: block;
    }


    /*-------------------------
        搜索输入框
    --------------------------*/

    .bar{
        background-color:#5c9bb7;

        background-image:-webkit-linear-gradient(top, #5c9bb7, #5392ad);
        background-image:-moz-linear-gradient(top, #5c9bb7, #5392ad);
        background-image:linear-gradient(top, #5c9bb7, #5392ad);

        box-shadow: 0 1px 1px #ccc;
        border-radius: 2px;
        width: 400px;
        padding: 14px;
        margin: 45px auto 20px;
        position:relative;
    }

    .bar input{
        background:#fff no-repeat 13px 13px;
        background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyBpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBXaW5kb3dzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkU5NEY0RTlFMTA4NzExRTM5RTEzQkFBQzMyRjkyQzVBIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkU5NEY0RTlGMTA4NzExRTM5RTEzQkFBQzMyRjkyQzVBIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6RTk0RjRFOUMxMDg3MTFFMzlFMTNCQUFDMzJGOTJDNUEiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6RTk0RjRFOUQxMDg3MTFFMzlFMTNCQUFDMzJGOTJDNUEiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4DjA/RAAABK0lEQVR42pTSQUdEURjG8dOY0TqmPkGmRcqYD9CmzZAWJRHVRIa0iFYtM6uofYaiEW2SRJtEi9YxIklp07ZkWswu0v/wnByve7vm5ee8M+85zz1jbt9Os+WiGkYdYxjCOx5wgFeXUHmtBSzpcCGa+5BJTCjEP+0nKWAT8xqe4ArPGEEVC1hHEbs2oBwdXkM7mj/JLZrad437sCGHOfUtcziutuYu2v8XUFF/4f6vMK/YgAH1HxkBYV60AR31gxkBYd6xAeF3VzMCwvzOBpypX8V4yuFRzX2d2gD/l5yjH4fYQEnzkj4fae5rJulF2sMXVrAsaTWttRFu4Osb+1jEDT71/ZveyhouTch2fINQL9hKefKjuYFfuznXWzXMTabyrvfyIV3M4vhXgAEAUMs7K0J9UJAAAAAASUVORK5CYII=);

        border: none;
        width: 100%;
        line-height: 19px;
        padding: 11px 0;

        border-radius: 2px;
        box-shadow: 0 2px 8px #c4c4c4 inset;
        text-align: left;
        font-size: 14px;
        font-family: inherit;
        color: #738289;
        font-weight: bold;
        outline: none;
        text-indent: 40px;
    }

    ul{
        list-style: none;
        width: 428px;
        margin: 0 auto;
        text-align: left;
    }

    ul li{
        border-bottom: 1px solid #ddd;
        padding: 10px;
        overflow: hidden;
    }

    ul li img{
        width:60px;
        height:60px;
        float:left;
        border:none;
    }

    ul li p{
        margin-left: 75px;
        font-weight: bold;
        padding-top: 12px;
        color:#6e7a7f;
    }
    </style>

</head>
<body>

<form id="main" v-cloak>

    <div class="bar">
        <!-- searchString 模型与文本域创建绑定 -->

        <input type="text" v-model="searchString" placeholder="输入搜索内容" />
    </div>

    <ul>
        <!-- 循环输出数据 -->
             
        <li v-for="article in filteredArticles">
            <a v-bind:href="article.url"><img v-bind:src="article.image" /></a>
            <p>{{article.title}}</p>
        </li>
    </ul>

</form>
<script>

var demo = new Vue({
    el: '#main',
    data: {
        searchString: "",

        // 数据模型,实际环境你可以根据 Ajax 来获取

        articles: [
            {
                "title": "What You Need To Know About CSS Variables",
                "url": "https://www.runoob.com/css/css-tutorial.html",
                "image": "https://static.runoob.com/images/icon/css.png"
            },
            {
                "title": "Freebie: 4 Great Looking Pricing Tables",
                "url": "https://www.runoob.com/html/html-tutorial.html",
                "image": "https://static.runoob.com/images/icon/html.png"
            },
            {
                "title": "20 Interesting JavaScript and CSS Libraries for February 2016",
                "url": "https://www.runoob.com/css3/css3-tutorial.html",
                "image": "https://static.runoob.com/images/icon/css3.png"
            },
            {
                "title": "Quick Tip: The Easiest Way To Make Responsive Headers",
                "url": "https://www.runoob.com/css3/css3-tutorial.html",
                "image": "https://static.runoob.com/images/icon/css3.png"
            },
            {
                "title": "Learn SQL In 20 Minutes",
                "url": "https://www.runoob.com/sql/sql-tutorial.html",
                "image": "https://static.runoob.com/images/icon/sql.png"
            },
            {
                "title": "Creating Your First Desktop App With HTML, JS and Electron",
                "url": "https://www.runoob.com/js/js-tutorial.html",
                "image": "https://static.runoob.com/images/icon/html.png"
            }
        ]
    },
    computed: {
        // 计算数学,匹配搜索
        filteredArticles: function () {
            var articles_array = this.articles,
                searchString = this.searchString;

            if(!searchString){
                return articles_array;
            }

            searchString = searchString.trim().toLowerCase();

            articles_array = articles_array.filter(function(item){
                if(item.title.toLowerCase().indexOf(searchString) !== -1){
                    return item;
                }
            })

            // 返回过来后的数组
            return articles_array;;
        }
    }
});
</script>
</body>
</html>

3.切换布局

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Vue.js 切换不同显示布局</title>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <style>
    /* 隐藏未编译的变量 */

    [v-cloak] {
      display: none;
    }

    *{
    	margin:0;
    	padding:0;
    }

    body{
    	font:15px/1.3 'Open Sans', sans-serif;
    	color: #5e5b64;
    	text-align:center;
    }

    a, a:visited {
    	outline:none;
    	color:#389dc1;
    }

    a:hover{
    	text-decoration:none;
    }

    section, footer, header, aside, nav{
    	display: block;
    }

    /*-------------------------
    	搜索框
    --------------------------*/

    .bar{
    	background-color:#5c9bb7;

    	background-image:-webkit-linear-gradient(top, #5c9bb7, #5392ad);
    	background-image:-moz-linear-gradient(top, #5c9bb7, #5392ad);
    	background-image:linear-gradient(top, #5c9bb7, #5392ad);

    	box-shadow: 0 1px 1px #ccc;
    	border-radius: 2px;
    	width: 580px;
    	padding: 10px;
    	margin: 45px auto 25px;
    	position:relative;
    	text-align:right;
    	line-height: 1;
    }

    .bar a{
    	background:#4987a1 center center no-repeat;
    	width:32px;
    	height:32px;
    	display:inline-block;
    	text-decoration:none !important;
    	margin-right:5px;
    	border-radius:2px;
    	cursor:pointer;
    }

    .bar a.active{
    	background-color:#c14694;
    }

    .bar a.list-icon{
    	background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyBpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyL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tldCBlbmQ9InIiPz4MjPshAAAAXklEQVR42mL4h/8I8B6IGaCYKHFGEMnAwCDIAAHvgZgRyiZKnImBQsACxB+hNoDAQyQ5osQZIT4gH1DsBZABH6AB8x/JaQzEig++WPiII7Rxio/GwmCIBYAAAwAwVIzMp1R0aQAAAABJRU5ErkJggg==);
    }

    .bar input{
    	background:#fff no-repeat 13px 13px;

    	border: none;
    	width: 100%;
    	line-height: 19px;
    	padding: 11px 0;

    	border-radius: 2px;
    	box-shadow: 0 2px 8px #c4c4c4 inset;
    	text-align: left;
    	font-size: 14px;
    	font-family: inherit;
    	color: #738289;
    	font-weight: bold;
    	outline: none;
    	text-indent: 40px;
    }

    /*-------------------------
    	列表布局
    --------------------------*/

    ul.list{
    	list-style: none;
    	width: 500px;
    	margin: 0 auto;
    	text-align: left;
    }

    ul.list li{
    	border-bottom: 1px solid #ddd;
    	padding: 10px;
    	overflow: hidden;
    }

    ul.list li img{
    	width:120px;
    	height:120px;
    	float:left;
    	border:none;
    }

    ul.list li p{
    	margin-left: 135px;
    	font-weight: bold;
    	color:#6e7a7f;
    }

    /*-------------------------
    	网格布局
    --------------------------*/

    ul.grid{
    	list-style: none;
    	width: 570px;
    	margin: 0 auto;
    	text-align: left;
    }

    ul.grid li{
    	padding: 2px;
    	float:left;
    }

    ul.grid li img{
    	width:280px;
    	height:280px;
    	object-fit: cover;
    	display:block;
    	border:none;
    }
    </style>

</head>
<body>

<form id="main" v-cloak>

	<div class="bar">

		<!-- 两个按钮用于切换不同的列表布局 -->

		<a class="list-icon" v-bind:class="{ 'active': layout == 'list'}" v-on:click="layout = 'list'"></a>
		<a class="grid-icon" v-bind:class="{ 'active': layout == 'grid'}" v-on:click="layout = 'grid'"></a>
	</div>

	<!-- 我们设置了两套布局页面。使用哪套依赖于 "layout" 绑定 -->

	<ul v-if="layout == 'grid'" class="grid">
		<!-- 使用大图,没有文本 -->
		<li v-for="a in articles">
			<a v-bind:href="a.url" target="_blank"><img v-bind:src="a.image.large" /></a>
		</li>
	</ul>

	<ul v-if="layout == 'list'" class="list">
		<!-- 使用小图及标题 -->
		<li v-for="a in articles">
			<a v-bind:href="a.url" target="_blank"><img v-bind:src="a.image.small" /></a>
			<p>{{a.title}}</p>
		</li>
	</ul>

</form>
<script>

    var demo = new Vue({
    	el: '#main',
    	data: {
            // 视图模型,可能的值是 "grid" 或 "list"。
    		layout: 'grid',

            articles: [{
                "title": "HTML 教程",
                "url": "https://www.runoob.com/html/html-tutorial.html",
                "image": {
                    "large": "https://static.runoob.com/images/mix/htmlbig.png",
                    "small": "https://static.runoob.com/images/icon/html.png"
                }
            },
            {
                "title": "CSS 教程",
                "url": "https://www.runoob.com/css/css-tutorial.html",
                "image": {
                    "large": "https://static.runoob.com/images/mix/cssbig.png",
                    "small": "https://static.runoob.com/images/icon/css.png"
                }
            },
            {
                "title": "JS 教程",
                "url": "https://www.runoob.com/js/js-tutorial.html",
                "image": {
                    "large": "https://static.runoob.com/images/mix/jsbig.jpeg",
                    "small": "https://static.runoob.com/images/icon/js.png"
                }
            },
            {
                "title": "SQL  教程",
                "url": "https://www.runoob.com/sql/sql-tutorial.html",
                "image": {
                    "large": "https://static.runoob.com/images/mix/sqlbig.png",
                    "small": "https://static.runoob.com/images/icon/sql.png"
                }
            },
            {
                "title": "Ajax 教程",
                "url": "https://www.runoob.com/ajax/ajax-tutorial.html",
                "image": {
                    "large": "https://static.runoob.com/images/mix/ajaxbig.png",
                    "small": "https://static.runoob.com/images/icon/ajax.png"
                }
            },
            {
                "title": "Python 教程",
                "url": "https://www.runoob.com/python/python-tutorial.html",
                "image": {
                    "large": "https://static.runoob.com/images/mix/pythonbig.png",
                    "small": "https://static.runoob.com/images/icon/python.png"
                }
            }]

    	}
    });
	
</script>
</body>
</html>

运行vue项目

// 1.打开终端
// 2.npm install  --->安装依赖
// 3.npm run serve   --->运行项目
// 4.npm run build    --->打包

分享

<share :config="config"></share>
//data:
config: {  //搜索配置i
                    sites: ['wechat','qq', 'weibo',  'douban'],
                    dispaly: ['google', 'facebook', 'twitter'],
                    wechatOrcodeTitle: '微信扫一扫:分享',
                    wechatOrcodeHelper: '

微信里点“发现”,扫一下

二维码便可将本文分享至朋友圈。

'
}, //引入share.css --->注:需放入fonts文件夹 @font-face{font-family:"socialshare";src:url("../fonts/iconfont.eot");src:url("../fonts/iconfont.eot?#iefix") format("embedded-opentype"),url("../fonts/iconfont.woff") format("woff"),url("../fonts/iconfont.ttf") format("truetype"),url("../fonts/iconfont.svg#iconfont") format("svg")}.social-share{font-family:"socialshare" !important;font-size:16px;font-style:normal;-webkit-font-smoothing:antialiased;-webkit-text-stroke-width:0.2px;-moz-osx-font-smoothing:grayscale}.social-share *{font-family:"socialshare" !important}.social-share .icon-tencent:before{content:"\f07a"}.social-share .icon-qq:before{content:"\f11a"}.social-share .icon-weibo:before{content:"\f12a"}.social-share .icon-wechat:before{content:"\f09a"}.social-share .icon-douban:before{content:"\f10a"}.social-share .icon-heart:before{content:"\f20a"}.social-share .icon-like:before{content:"\f00a"}.social-share .icon-qzone:before{content:"\f08a"}.social-share .icon-linkedin:before{content:"\f01a"}.social-share .icon-diandian:before{content:"\f05a"}.social-share .icon-facebook:before{content:"\f03a"}.social-share .icon-google:before{content:"\f04a"}.social-share .icon-twitter:before{content:"\f06a"}.social-share a{position:relative;text-decoration:none;margin:4px;display:inline-block;outline:none}.social-share .social-share-icon{position:relative;display:inline-block;width:32px;height:32px;font-size:20px;border-radius:50%;line-height:32px;border:1px solid #666;color:#666;text-align:center;vertical-align:middle;transition:background 0.6s ease-out 0s}.social-share .social-share-icon:hover{background:#666;color:#fff}.social-share .icon-weibo{color:#ff763b;border-color:#ff763b}.social-share .icon-weibo:hover{background:#ff763b}.social-share .icon-tencent{color:#56b6e7;border-color:#56b6e7}.social-share .icon-tencent:hover{background:#56b6e7}.social-share .icon-qq{color:#56b6e7;border-color:#56b6e7}.social-share .icon-qq:hover{background:#56b6e7}.social-share .icon-qzone{color:#FDBE3D;border-color:#FDBE3D}.social-share .icon-qzone:hover{background:#FDBE3D}.social-share .icon-douban{color:#33b045;border-color:#33b045}.social-share .icon-douban:hover{background:#33b045}.social-share .icon-linkedin{color:#0077B5;border-color:#0077B5}.social-share .icon-linkedin:hover{background:#0077B5}.social-share .icon-facebook{color:#44619D;border-color:#44619D}.social-share .icon-facebook:hover{background:#44619D}.social-share .icon-google{color:#db4437;border-color:#db4437}.social-share .icon-google:hover{background:#db4437}.social-share .icon-twitter{color:#55acee;border-color:#55acee}.social-share .icon-twitter:hover{background:#55acee}.social-share .icon-diandian{color:#307DCA;border-color:#307DCA}.social-share .icon-diandian:hover{background:#307DCA}.social-share .icon-wechat{position:relative;color:#7bc549;border-color:#7bc549}.social-share .icon-wechat:hover{background:#7bc549}.social-share .icon-wechat .wechat-qrcode{display:none;border:1px solid #eee;position:absolute;z-index:9;top:-205px;left:-84px;width:200px;height:192px;color:#666;font-size:12px;text-align:center;background-color:#fff;box-shadow:0 2px 10px #aaa;transition:all 200ms;-webkit-tansition:all 350ms;-moz-transition:all 350ms}.social-share .icon-wechat .wechat-qrcode.bottom{top:40px;left:-84px}.social-share .icon-wechat .wechat-qrcode.bottom:after{display:none}.social-share .icon-wechat .wechat-qrcode h4{font-weight:normal;height:26px;line-height:26px;font-size:12px;background-color:#f3f3f3;margin:0;padding:0;color:#777}.social-share .icon-wechat .wechat-qrcode .qrcode{width:105px;margin:10px auto}.social-share .icon-wechat .wechat-qrcode .qrcode table{margin:0 !important}.social-share .icon-wechat .wechat-qrcode .help p{font-weight:normal;line-height:16px;padding:0;margin:0}.social-share .icon-wechat .wechat-qrcode:after{content:'';position:absolute;left:50%;margin-left:-6px;bottom:-13px;width:0;height:0;border-width:8px 6px 6px 6px;border-style:solid;border-color:#fff transparent transparent transparent}.social-share .icon-wechat:hover .wechat-qrcode{display:block}

获取返回的登录信息(vuex)

this.$store.state

this.$message信息弹出后执行的操作

this.$message({
    message: res.message,
    center: true,
    onClose: () => {
      this.$router.push("/");
    },
});

组件(例:发送验证码)

//公共部分写成组件,放在components下
<template>
  <!--    //发送验证码按钮组件-->
  <div v-loading="loading">
    <el-button
      type="primary"
      @click="sendcode"
      :disabled="disabled"
      v-if="disabled == false"
      >发送验证码
    </el-button>
    <el-button
      type="button"
      @click="sendcode"
      :disabled="disabled"
      v-if="disabled == true"
      >{{ btntxt }}
    </el-button>
  </div>
</template>

<script>
export default {
  name: "CodeBtn",
  props: {
    phone: String,
    codeType: {
      //getCode注册,getCode2登录,getCode3重置手机号,getCode4路演报名,getCode5融资申请
      type: String,
      default: "getCode",
    },
  },
  data() {
    return {
      disabled: false,
      btntxt: "重新发送",
      time: 0,
      loading: false,
    };
  },
  methods: {
    async getCode() {
      let phone = this.phone;
      this.loading = true;
      let res = await this.$api[this.codeType]({ phone });
      this.loading = false;
      if (res.success) {
        this.$message({
          message: "发送成功",
          type: "success",
          center: true,
        });
        this.time = 60;
        this.disabled = true;
        this.timer();
      }
    },
    sendcode() {
      const reg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/;
      if (this.phone == "") {
        this.$message({
          message: "手机号不能为空",
          center: true,
        });
        return;
      }
      if (!reg.test(this.phone)) {
        this.$message({
          message: "请输入正确的手机号",
          center: true,
        });
        return;
      } else {
        this.getCode();
      }
    },
    //60S倒计时
    timer() {
      if (this.time > 0) {
        this.time--;
        this.btntxt = this.time + "s后重新获取";
        setTimeout(this.timer, 1000);
      } else {
        this.time = 0;
        this.btntxt = "获取验证码";
        this.disabled = false;
      }
    },
  },
};
</script>

<style scoped></style>



//在使用的地方引用
<CodeBtn :phone="form.phone" codeType="getCode"></CodeBtn>
//js处引入
import CodeBtn from "../../components/logincpn/CodeBtn";
//js最后引入
components: {
    CodeBtn,
  },

登录后将token及用户信息存储起来

this.$store.commit('setToken',res.result.token);
this.$store.commit('setUserInfo',res.result.user);

解决路由不置顶问题

Vue.use(VueRouter)
const routes = [{
        path: '/register',  //注册
        name: 'register',
        component: Register,
        meta: {
            keepAlive: false,
            auto:true, //不登录也能访问该页面
            tabbar_active: 'register'
        }
    },
    {
        path: '/login',  //登录
        name: 'login',
        component: Login,
        meta: {
            keepAlive: false,
            auto:true, //不登录也能访问该页面
            tabbar_active: 'login'
        }
    }]
const router = new VueRouter({
    scrollBehavior(to, from, savedPosition) { //解决路由跳转后不置顶问题
        if(!to.matched[0].meta.childDisScroll){ //判断路由的父路由childDisScroll为true则刷新该页面不置顶,
            if (savedPosition) {
                return savedPosition
            }
            return {
                x: 0,
                y: 0
            }
        }
    },
    routes
})

封装

//store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        activePage: 'home', //启动页
        token: '',
        userInfo: '', //其中身份type: 1政府 2企业
        beforeLoginPage:'', //跳转登录之前的页面路由
    },
    mutations: {
        changeBeforeLoginPage(state, payload){
            state.beforeLoginPage = payload
        },
        changeActive(state, payload) {
            state.activePage = payload;
        },
        setUserInfo(state, payload) {
            state.userInfo = payload;
            window.sessionStorage.setItem('userInfo', JSON.stringify(payload))
        },
        setToken(state, payload) {
            state.token = payload
            window.sessionStorage.setItem('token', payload)
        }
    },
    actions: {},
    getters: {
        getStorage(state) {
            if (!state.token) {
                state.token = sessionStorage.getItem('token');
                state.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
            }
            return state.token
        },
    },
    modules: {}
})

//base.js(接口地址)
const BASE_URL = 'http://ipo.hebotc.com/guquan/'
// const BASE_URL = 'http://192.168.0.121:8090/jeecg-boot/'
export default {
    domainURL: BASE_URL + 'sys/common/static/',
}
//axios.js(封装请求)
//封装axios
import axios from 'axios'
import qs from 'qs'; // 根据需求是否导入qs模块
import store from '../../store/index'
import { Message } from 'element-ui';
import methods from "../methods";
import he from "element-ui/src/locale/lang/he";

// 创建axios实例
const service = axios.create({});
service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
// request拦截器
service.interceptors.request.use(
    config => {
        return config;
    },
    error => {
        Promise.reject(error);
    }
);
// response拦截器
service.interceptors.response.use(
    response => {
        if (response) {
            if(!response.data.success){
                if(response.data.message.indexOf('token失效') != -1){
                    methods.toLogin(response.data.message)
                }else {
                    Message({
                        message:response.data.message,
                        center:true
                    })
                }

            }
            return response.data;
        } else {
            Promise.reject(new Error("error"));
        }
    },
    error => {
        Message({
            message:error,
            center:true
        })
        return Promise.reject(error);
    }
);

export default {
    get(url, params) {
        let token = store.state.token;
        return new Promise((resolve, reject) => {
            service.get(url, {params:{...params,token}}).then((res) => {
                resolve(res)
            }).catch((err) => {
                reject(err)
            })
        })
    },
    post(url, params,header,isQs = false ) { //接口地址,参数,请求头,是否qs序列化
        let token = store.state.token;
        let headers = header?{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}:{}
        params = isQs? qs.stringify({...params,token}) : {...params,token}
        return new Promise((resolve, reject) => {
            service.post(url, params,headers).then((res) => {
                resolve(res)
            }).catch((err) => {
                reject(err)
            })
        })
    }
};
//api.js
import base from "./base";
import axios from "./axios";

export default {
    async testPost(params = {}){
        let res = await axios.post(base.test,params)
        return res;
    }
}

elementui分页

<div class="paginationbox">
    <el-pagination
          background
          v-if="show_page"
          :current-page="pageNo"
          :page-size="pageSize"
          @current-change="currentChange"
          layout="prev, pager, next"
          :page-count="pageCount">
    </el-pagination>
</div>
<script>
    export default {
        name: "tutoringTable",
        props: {
            companyName: String,
            type: String,
        },
        data() {
            return {
                show_page: true,
                pageSize: 10, //每页显示数量
                pageCount: 1, //数据总数
                pageNo: 1,
                result: []
            }
        },
        watch: {
            type(data) {
                this.getMsg()
                this.pageNo = 1;
            },
            companyName() {
                this.pageNo = 1;
            }
        },
        mounted() {
            this.getMsg()
        },
        methods: {
            toDetail() {
                this.$router.push('/companyProfiles')
            },
            currentChange(e) {
                //页数改变
                this.pageNo = e;
                this.getMsg();
            },
            async getMsg() {
               //页码更新问题
                this.page_show = false
                let companyName = this.companyName;
                let pageNo = this.pageNo
                let type = this.type
                let res = await this.$api.fudaoCompany({companyName, pageNo, type});
                this.result = res.result.records
                this.pageCount = res.result.pages
                //页码更新问题
                this.$nextTick(()=>{
                    this.page_show = true
                })
            }
        }
    }
</script>

localStorage

//store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        activePage: 'home',
        token: localStorage.getItem("token")  || '',
        userInfo: JSON.parse(localStorage.getItem("userInfo")) || '', //其中身份type: 1政府 2企业
        beforeLoginPage:'', //跳转登录之前的页面路由
    },
    mutations: {
        changeBeforeLoginPage(state, payload){
            state.beforeLoginPage = payload
        },
        changeActive(state, payload) {
            state.activePage = payload;
        },
        setUserInfo(state, payload) {
            state.userInfo = payload;
            window.sessionStorage.setItem('userInfo', JSON.stringify(payload))
        },
        setToken(state, payload) {
            state.token = payload
            window.sessionStorage.setItem('token', payload)
        },
    },
    actions: {},
    getters: {
        getStorage(state) {
            if (!state.token) {
                state.token = sessionStorage.getItem('token');
                state.userInfo = JSON.parse(localStorage.getItem('userInfo'))
            }
            return state.token
        },
    },
    modules: {}
})

//login
<template>
    <section id="back">
        <div class="sectionin w clearfix">
            <div class="sectioninleft">
                <p class="p1">
                    欢迎来到
                </p>
                <p class="p2">
                    河北省企业股改上市服务平台
                </p>
                <div class="tiao"></div>
            </div>
            <div class="sectioninright" v-loading="loading">
                <div class="title">
                    <div :class="{'active':identity==1}" id="zflink" @click="changeIdentity(1)">
                        <span class="svg1">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#iconqiye"></use>
                            </svg>
                        </span>
                        <span class="acspan">政府登录</span>
                    </div>
                    <div :class="{'active':identity==2}" id="qylink" @click="changeIdentity(2)">
                        <span class="svg1">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#iconqiye"></use>
                            </svg>
                        </span>
                        <span class="acspan">企业登录</span>
                    </div>
                </div>
                <div class="tab" v-if="identity==2" id="qybox">
                    <div class="anniugroup">
                        <div class="anniu" :class="{'anniu_active':loginType==1}" @click="changeLoginType(1)" >
                            短信验证登录
                        </div>
                        <div class="anniu" :class="{'anniu_active':loginType==2}" @click="changeLoginType(2)">
                            密码登录
                        </div>
                    </div>
                    <LoginInPhone @submit="submit" v-if="loginType==1"></LoginInPhone>
                    <LoginInName @submit="submit" v-else></LoginInName>
                     <p class="hmzh">
                         还没账号<router-link tag="a" to="/register">快速注册</router-link>
                     </p>
                </div>
                <div class="tab" style="margin-top: 90px" v-else id="zfbox">
                    <LoginInName @submit="submit"></LoginInName>
                </div>
            </div>
        </div>
    </section>
</template>

<script>
    import LoginInName from "../../components/logincpn/LoginInName";
    import LoginInPhone from "../../components/logincpn/LoginInPhone";
    export default {
        name: "Login",
        data(){
            return{
                identity:1,
                loginType:1,
                loading:false,
            }
        },
        computed:{
          login(){ //修改登录接口
              if(this.identity==1){
                 return 'loginInPwd2'
              }else if(this.identity==2){
                 if(this.loginType==1){
                     return 'loginInCode'
                 } else {
                     return 'loginInPwd'
                 }
              }
          }
        },
        mounted() {
            let token = localStorage.getItem("token")
            if(token) {
                this.$router.push('/')
            }
        },
        methods:{
            async getCode(params){
                try{
                    let res = await this.$api[this.login](params);
                    this.loading = false;
                    let type = res.result.user.type;
                    this.$store.commit('setToken',res.result.token);
                    this.$store.commit('setUserInfo',res.result.user);
                    localStorage.setItem('token',res.result.token)
                    localStorage.setItem('userInfo',JSON.stringify(res.result.user))
                    
                    this.toCenter(type)
                    // type
                    // console.log(res.result.user)
                }catch (e) {
                    this.loading = false;
                }
            },
            changeIdentity(i){
                this.identity = i
            },
            changeLoginType(i){
                this.loginType = i
            },
            toCenter(type){
                let page = this.$store.state.beforeLoginPage;
                if(page){
                    this.$router.push(page)
                }else {
                    if(type==1){
                        //政府登录
                        this.$router.push('/govermentCenter')
                    }else if(type==2){
                        //企业登录
                        this.$router.push('/companyCenter')
                    }
                }



            },
            companyLogin(){

            },
            submit(data){
                // console.log('登录0');
                // console.log(data);
                this.loading = true;
                this.getCode(data)
            }

        },
        created() {

        },
        components: {
            LoginInName,LoginInPhone
        }
    }
</script>

//公共header
<template>
    <!-- 头部代码 -->
    <header>
        <div class="head w">
            <div class="box1">
                <div class="left-text">
                    您好,欢迎来到河北省企业股改上市服务平台
                </div>
                <div class="right-img">
                    <img src="../static/img/heaedr-right.jpg" alt="">
                </div>
            </div>
            <div class="box2">
                <router-link to="/" tag="div" class="left">
                    <img src="../static/img/logo.jpg" alt="">
                    <span>河北省企业股改上市服务平台</span>
                </router-link>
                <div class="right" v-if="!token">
                    <p><router-link tag="a" to="/register">注册</router-link><span>/</span><router-link tag="a" to="/login">登录</router-link></p>
                    <img src="../static/img/user.jpg" alt="">
                </div>
                <div class="right" v-else>
                    <p><a @click="toCenter(userInfo.type)"><if condition="userInfo.companyName neq ''">{{userInfo.companyName}}</if></a>
                        <span>/</span>
                        <a @click="logOut">退出登录</a></p>
                    <img src="../static/img/user.jpg" alt="">
                </div>
            </div>
        </div>
    </header>
</template>

<script>
    export default {
        name: "Header",
        data(){
            return {
                name:'',
                child1:false,
                child2:false,
            }
        },
        mounted(){
      
        },
        methods:{
            to(path){
                this.$router.push({path})
            },
            toCenter(type){
                if(type==1){
                    this.to('/govermentCenter') //政府
                }else if(type==2){
                    this.to('/companyCenter') //企业
                }
            },
            logOut(){
                window.sessionStorage.clear();//清除session所有数据
                window.localStorage.clear() 
                this.$store.commit('setToken','');
                this.$store.commit('setUserInfo','');
                this.to('/login') //登录
                location.reload()
            }

        },
        computed:{
            token(){
                return this.$store.state.token;
            },
            userInfo(){
                return this.$store.state.userInfo;
            },
            companyName(){
                return this.$store.state.companyName;
            },
            activeRouter(){
                if(this.$route.meta.tabbar_active){
                    return this.$route.meta.tabbar_active
                }else {
                    return this.$store.state.activePage
                }
            }
            
        },
    }
</script>

//APP.vue
//退出浏览器清除缓存
mounted() {
    window.addEventListener('beforeunload',()=>{
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');

    });
  },

你可能感兴趣的:(vue.js)