依照Vue的WebApp项目支出,文件操作

2019-05-25 17:30 来源:未知

xml文件:

实现商品购买列表页面

文件操作,c 文件操作

www.weide1946.com 1www.weide1946.com 2

步骤一:新建goodslist.vue文件

文件操作

对文件操作流程

现有文件如下 :文件名为“song”

 1 hiding from the rain and snow 
 2 藏身于雨雪之中  
 3 trying to forget but i won't let go 
 4 努力忘记,但我怎能就这样离去  
 5 looking at a crowded street 
 6 看着熙熙攘攘的街道  
 7 listening to my own heart beat 
 8 却只能听见自己的心跳  
 9 so many people all around the world 
10 这么多的人在世界上  
11 tell me where do i find someone like you girl 
12 请告诉我在哪里可以找到像你一样的女孩   
13 take me to your heart take me to your soul 
14 将我留存心间与你的灵魂相伴  
15 give me your hand before i'm old 
16 给我你的手,在我老去之前  
17 show me what love is haven't got a clue 
18 问情为何物在我们彼此离开前  
19 show me that wonders can be true 
20 问奇迹上演  
21 they say nothing lasts forever 
22 他们说没有什么可以天长地久  
23 we're only here today 
24 我们也能此时相守  
25 love is now or never 
26 现在或者永不回头  
27 bring me far away 
28 请带我一起远走 

基本操作:

#r只读模式

www.weide1946.com 3

f=open('song','r',encoding='utf-8') #打开文件,赋给文件句柄f(f实际上就是该文件的内存对象)
data1=f.readline()#读一行
data2=f.read()## 读取剩下的所有内容,文件大时不要用,不一定能全读回来
print(data1)
print(data2)

View Code

#其他的一些操作
f.tell()#查看文件句柄指针的位置
print(f.tell())
f.seek(0)#设置文件的当前位置偏移
print(f.tell())
print(data1)
print(f.encoding)#文件的编码方式
print(f.fileno())#文件的编号
f.close()#关闭打开的文件,关闭的文件无法读取或写入更多东西
f.flush()#刷新
f.truncate()#截取,从文件句柄指针位置开始,若没有参数就清空

#f.readlines() 方法会先把所有行读到内存里 效率低下 ,一般不用

www.weide1946.com 4

#low loop
for index line in enumerate(f.readlines()):
    if index=9:
       print("------我是分割线-------")
    print(line.strip())#去空行

View Code

 既然readlines()方法效率低下,那么问题来了,我们应该用什么高效的方法呢?

www.weide1946.com 5

#high
count=0
for line in f: #一行行地读,并且内存里只保存一行
    if count==9:
        print("-----我是分割线-------")
        count  = 1
        continue
    count =1
    print(line)
f.close()

#此时f不像上面readlines那样是个列表,不能通过枚举的方法打印所需的行,只能通过自定义一个计数器

View Code

#w 只写模式 倘若被写入文件中有内容,则会被覆盖掉

www.weide1946.com 6

f1=open('song2','w',encoding='utf-8')
f1.write('苍茫的天涯是我的爱n')
f1.write('绵绵的青山脚下花正开n')

View Code

# a=append 后面追加 默认不能读

www.weide1946.com 7

f2=open('song2','a',encoding="utf-8") #文件句柄 追加
f2.write("什么样的节奏是最呀最摇摆n")
# f2.flush()#刷新

View Code

# 读写模式 r  以读和追加的方式

www.weide1946.com 8

f=open('song2','r ') #文件句柄 读&追加
print(f.readline())
print(f.readline())
f.write("什么样的节奏是最呀最摇摆n")
f.write("什么样的歌声...n")
f.close()

View Code

#写读模式 w 

www.weide1946.com 9

f3=open('song3',"w ",encoding='utf-8') #文件句柄 写读
f3.write("""
静静地陪你走了好远好远

连眼睛红了

都没有发现

听着你说你现在的改变

看着我依然最爱你的笑脸

这条旧路依然没有改变
""")
f3.seek(2)
print(f3.readline())
f3.close()

View Code

#追加读 a  既能追加也可以读

www.weide1946.com 10

f4=open("song3","a ",encoding='utf-8')
f4.write("""
以往的每次路过都是晴天

想起我们有过的从前

泪水就一点一点开始蔓延
""")
f4.seek(30)
print(f4.readline())
f4.close()

View Code

#二进制读

www.weide1946.com 11

f5=open('song','rb') #文件句柄 二进制文件
print(f5.readline())
print(f5.readline())
print(f5.readline())
f5.close()

View Code

#二进制写入

www.weide1946.com 12

f6=open('song4','wb') #文件句柄 二进制文件
f6.write("Hello binary !n".encode())
f6.close()

View Code

#修改文件

www.weide1946.com 13

f=open('song','r',encoding='utf-8')
f_new=open('song_修改版','w',encoding="utf-8")
for line in f:
    if "我" in line:
        line=line.replace('我','哥')
    f_new.write(line)
f.close()
f_new.close()

View Code

 

with语句

  为了避免打开文件后忘记关闭,可以通过with管理上下文:

with open('song','r',encoding='utf-8') as f:
    for line in f:
        print(line)
#如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

#在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,如:
with open('song1','r',encoding='utf-8') as f,open('song2','r',encoding='utf-8')as f1:
    pass

 

文件操作 对文件操作流程 现有文件如下 :文件名为“song” 1 hiding from therain and snow 2 藏身于雨雪之中 3 tryingtoforg...

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <orders> <!-- 所有订单信息 -->
 3     <order> <!-- 订单,至少包含1个订单 -->
 4         <orderDate>2018-05-20</orderDate><!--orderDate为日期型 -->
 5         <shipTo country="CN"><!-- 配送信息,country属性必须出现 -->
 6             <name>张三峰</name> <!-- 收件人,长度小于50 -->
 7             <street>市中区滨河路778号5 3大酒店</street> <!-- 县/区及街道地址 -->
 8             <city>乐山市</city> <!-- 市/区,长度小于50 -->
 9             <state>四川省</state> <!-- 省/自治区/直辖市,长度小于50 -->
10             <phone>13999999999</phone> <!-- 联系电话,要求必须是1开头,后面第2位数字3-9,再后面是9个数字 -->
11         </shipTo>
12         <items> <!-- 商品列表,item应至少出现1次 -->
13             <item partNum="872-AA"> <!-- 商品编号属性,必须有 -->
14                 <productName>香辣鸡翅</productName><!-- 商品名称,长度小于50 -->
15                 <quantity>1</quantity> <!-- 购买数量,至少是1 -->
16                 <price>18.95</price> <!-- 单价为浮点数,大于0.0 -->
17                 <shipDate>2018-05-21</shipDate> <!-- 配送日期 -->
18             </item>
19             <item partNum="926-AA">
20                 <productName>烧烤五花肉</productName>
21                 <quantity>20</quantity>
22                 <price>39.98</price>
23                 <shipDate>2018-05-20</shipDate>
24             </item>
25         </items>
26     </order>
27 </orders>

www.weide1946.com 14www.weide1946.com 15

View Code

<template>
  <div id="tml">
    <!--利用mui中的图文表格组件实现-->
    <div id="mui-content" class="mui-content" style="background-color:#fff">
      <ul class="mui-table-view mui-grid-view">
        <li v-for="item in list" class="mui-table-view-cell mui-media mui-col-xs-6">
          <router-link v-bind="{to:'/goods/goodsinfo/' item.id}">
            <img class="mui-media-object" :src="item.img_url" style="height: 250px;">
            <div class="mui-media-body" v-text="item.title"></div>
            <div class="desc">
              <p>
                ¥{{item.sell_price}}
                <s>¥{{item.market_price}}</s>
              </p>
              <p>
                <h6 class="left">热卖中</h6>
                <h6 class="right">剩余{{item.stock_quantity}}件</h6>
              </p>
            </div>
          </router-link>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
  import { Toast } from 'mint-ui';
  // 代表vm
  export default {
    data() {
      return {
        list: []
      }
    },
    created() {
      this.getlist();
    },
    methods: {
      getlist() {
        //获取到商品列表数据
        var url = '../../../statics/json/goodslist.json';
        this.$http.get(url).then(function(res) {
          if(res.body.status != 0) {
            Toast(res.body.message);
            return;
          }
          //当服务器返回了正常数据的时候做赋值操作
          this.list = res.body.message;
        });
      }
    }
  }
</script>

<style scoped>
  #mui-content li {
    border: 1px solid rgba(0, 0, 0, 0.4);
    -webkit-box-shadow: 0 0 4px #000;
    -moz-box-shadow: 0 0 4px #000;
    box-shadow: 0 0 4px #000;
    margin-left: 4px;
    padding: 0px;
    background-color: #fff;
    margin-bottom: 6px;
  }  
  #mui-content .mui-media-body {
    color: #0094ff;
  } 
  #mui-content .desc {
    height: 60px;
    background-color: rgba(0, 0, 0, 0.2);
    margin-top: 10px;
    padding: 5px;
    text-align: left;
  } 
  #mui-content .desc span {
    color: #a22b2b;
    margin-right: 15px;
  }  
  #mui-content a {
    padding-left: 0px;
    margin-left: 0px;
  }  
  #mui-content .desc .right {
    position: absolute;
    right: 10px;
    bottom: 0px;
    font-weight: bold;
  }  
  #mui-content .desc .left {
    position: absolute;
    left: 10px;
    bottom: 0px;
    color: red;
    font-weight: bold;
  }
</style>

xsd文件:

View Code

www.weide1946.com 16www.weide1946.com 17

步骤二:新建goodslist.json文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
 3     <xsd:element name="orders">
 4         <xsd:complexType>
 5             <xsd:sequence>
 6                 <xsd:element ref="order" minOccurs="1"></xsd:element>
 7             </xsd:sequence>
 8         </xsd:complexType>
 9     </xsd:element>
10     
11     <xsd:element name="order" >
12         <xsd:complexType>
13             <xsd:sequence>
14                 <xsd:element ref="orderDate"></xsd:element>
15                 <xsd:element ref="shipTo"></xsd:element>
16                 <xsd:element ref="items" minOccurs="1"></xsd:element>
17             </xsd:sequence>
18         </xsd:complexType>
19     </xsd:element>
20     
21     <xsd:element name="orderDate" type="xsd:date"></xsd:element>    
22         <xsd:element name="shipTo">
23         <xsd:complexType>
24             <xsd:sequence>
25                 <xsd:element ref="name"></xsd:element>
26                 <xsd:element ref="street"></xsd:element>
27                 <xsd:element ref="city"></xsd:element>
28                 <xsd:element ref="state"></xsd:element>
29                 <xsd:element ref="phone"></xsd:element>
30             </xsd:sequence>
31             <xsd:attribute name="country"  type="xsd:string" use="required"></xsd:attribute>
32         </xsd:complexType>
33     </xsd:element>
34     <xsd:element name="items">
35         <xsd:complexType>
36             <xsd:sequence>
37                 <xsd:element ref="item" minOccurs="1" maxOccurs="unbounded"></xsd:element>
38             </xsd:sequence>
39         </xsd:complexType>
40     </xsd:element>
41     
42     <xsd:element name="item">
43         <xsd:complexType>
44             <xsd:sequence>
45                 <xsd:element ref="productName"></xsd:element>
46                 <xsd:element ref="quantity"></xsd:element>
47                 <xsd:element ref="price"></xsd:element>
48                 <xsd:element ref="shipDate"></xsd:element>
49             </xsd:sequence>
50             <xsd:attribute name="partNum"  type="xsd:string" use="required"></xsd:attribute>
51         </xsd:complexType>
52     </xsd:element>
53     
54     <xsd:element name="name" type="nameType"></xsd:element>
55     <xsd:element name="street" type="xsd:string"></xsd:element>
56     <xsd:element name="city" type="nameType"></xsd:element>
57     <xsd:element name="state" type="nameType"></xsd:element>
58     <xsd:element name="phone" type="phoneType"></xsd:element>
59     
60     <xsd:element name="productName" type="nameType"></xsd:element>
61     <xsd:element name="quantity" type="xsd:positiveInteger"></xsd:element>
62     <xsd:element name="price" type="priceType"></xsd:element>
63     <xsd:element name="shipDate" type="xsd:date"></xsd:element>
64     
65 
66     <xsd:simpleType name="nameType">
67         <xsd:restriction base="xsd:string">
68             <xsd:minLength value="0"></xsd:minLength>
69             <xsd:maxLength value="50"></xsd:maxLength>
70         </xsd:restriction>
71     </xsd:simpleType>
72     <xsd:simpleType name="phoneType">
73         <xsd:restriction base="xsd:integer">
74             <xsd:pattern value="1[3-9]{1}[0-9]{9}"></xsd:pattern>
75         </xsd:restriction>
76     </xsd:simpleType>
77     <xsd:simpleType name="priceType">
78         <xsd:restriction base="xsd:float">
79              <xsd:minInclusive value="0.1"></xsd:minInclusive>
80         </xsd:restriction>
81     </xsd:simpleType>
82     
83     
84 </xsd:schema>

www.weide1946.com 18www.weide1946.com 19

View Code

{
  "status": 0,
  "message": [
    {
      "id": 1,
      "title": "动漫被套床单",
      "add_time": "2017-12-25",
      "zhaiyao": "尺寸图样皆可以订制,如果在店铺展示页面没有喜欢的角色,可以咨询客服,查看图库,进行选取!",
      "click": 30,
      "img_url": "../../statics/imgs/goodslist/goodslist01.jpg",
      "sell_price": 78,
      "market_price": 68,
      "stock_quantity": 200,
      "goods_no": "SD13313123"
    }, {
      "id": 2,
      "title": "二次元毛绒抱枕",
      "add_time": "2017-12-25",
      "zhaiyao": "此优惠限5件,超出则该商品全部恢复非活动价",
      "click": 33,
      "img_url": "../../statics/imgs/goodslist/goodslist02.jpg",
      "sell_price": 58,
      "market_price": 63,
      "stock_quantity": 500
    }, {
      "id": 3,
      "title": "逍遥宅品猫咪痛包",
      "add_time": "2017-12-25",
      "zhaiyao": "一共是一个外包 印花猫咪内包 纯色内包 肩带 手拎带。自由发挥自主搭配!带子之后会换成皮的!",
      "click": 34,
      "img_url": "../../statics/imgs/goodslist/goodslist03.jpg",
      "sell_price": 57,
      "market_price": 63,
      "stock_quantity": 500
    }, {
      "id": 4,
      "title": "动漫周边保温杯",
      "add_time": "2017-12-25",
      "zhaiyao": "采用304不锈钢 双层真空内胆 保温久不烫手 支持来图定制 买就送杯套",
      "click": 36,
      "img_url": "../../statics/imgs/goodslist/goodslist04.jpg",
      "sell_price": 80,
      "market_price": 100,
      "stock_quantity": 300
    }, {
      "id": 5,
      "title": "雪初音卫衣棉服",
      "add_time": "2017-12-25",
      "zhaiyao": "此优惠限5件,超出则该商品全部恢复非活动价",
      "click": 63,
      "img_url": "../../statics/imgs/goodslist/goodslist05.jpg",
      "sell_price": 66,
      "market_price": 80,
      "stock_quantity": 300
    }, {
      "id": 6,
      "title": "Monchhichi萌趣趣",
      "add_time": "2017-12-25",
      "zhaiyao": "Monchhichi萌趣趣十二生肖狗鸡小兔马羊龙老虎猪小鸡公仔送人礼品",
      "click": 38,
      "img_url": "../../statics/imgs/goodslist/goodslist06.jpg",
      "sell_price": 75,
      "market_price": 90,
      "stock_quantity": 800
    }
  ]
}

验证XML的Java文件:

View Code

www.weide1946.com 20www.weide1946.com 21

步骤三:在入口文件main.js中配置好路由规则

 1 import java.io.File;
 2 
 3 import javax.xml.transform.stream.StreamSource;
 4 import javax.xml.validation.Schema;
 5 import javax.xml.validation.SchemaFactory;
 6 import javax.xml.validation.Validator;
 7 
 8 import org.xml.sax.SAXException;
 9 import org.xml.sax.SAXParseException;
10 import org.xml.sax.helpers.DefaultHandler;
11 
12 public class TestSchema {
13 
14     public static void main(String[] args) {
15         File xsdfile = new File("order.xsd");
16         File xmlfile = new File("orders.xml");
17         Handler errorHandler = null;
18         try {
19             SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
20             Schema schema = schemaFactory.newSchema(xsdfile);
21             Validator validator = schema.newValidator();
22             errorHandler = new Handler();
23             validator.setErrorHandler(errorHandler);
24             validator.validate(new StreamSource(xmlfile));
25         } catch (Exception e) {
26             System.out.println(e);
27         }
28         if (errorHandler.errorMessage == null) {
29             System.out.println("XML 文件:"   xmlfile.getName() "符合模式");
30         } else {
31             System.out.println("XML 文件:"   xmlfile.getName() "不符合模式");
32         }
33     }
34 }
35 
36 class Handler extends DefaultHandler {
37     String errorMessage = null;
38     
39     public void error(SAXParseException e) throws SAXException {
40         errorMessage = e.getMessage();
41         int row = e.getLineNumber();
42         int colums = e.getColumnNumber();
43         System.out.println("一般错误" errorMessage "位置:" row "," colums);
44     }
45     
46     public void fatalError(SAXParseException e) throws SAXException {
47         errorMessage = e.getMessage();
48         int row = e.getLineNumber();
49         int colums = e.getColumnNumber();
50         System.out.println("致命错误" errorMessage "位置:" row "," colums);
51     }
52 }

www.weide1946.com 22www.weide1946.com 23

View Code

//导入vue核心包
import Vue from 'vue';

//导入App.vue的vue对象
import App from './App.vue';

//导入vue-router
import vueRouter from 'vue-router';

//将vueRouter对象绑定到Vue对象上
Vue.use(vueRouter);

//导入路由规则对应的组件对象
import home from './components/Home.vue';
import shopcar from './components/shopcar/car.vue';
import newslist from './components/news/newslist.vue';
import newsinfo from './components/news/newsinfo.vue';
import photolist from './components/photo/photolist.vue';
import photoinfo from './components/photo/photoinfo.vue';
import goodslist from './components/goods/goodslist.vue';

//定义路由规则
var router1 = new vueRouter({
    //改变路由激活时的class名称
  linkActiveClass: 'mui-active', 
  routes: [{
      path: '/',
      component: home 
    }, {
      path: '/home',
      component: home
    },
    {
      path: '/shopcar',
      component: shopcar
    },
    {
      path: '/news/newslist',
      component: newslist
    },
    {
      path: '/news/newsinfo/:id',
      component: newsinfo
    },
    {
      path: '/photo/photolist',
      component: photolist
    },
    {
      path: '/photo/photoinfo/:id',
      component: photoinfo
    },
    {
      path: '/goods/goodslist',
      component: goodslist
    }
  ]
});

//导入mint-ui的css文件
import 'mint-ui/lib/style.min.css';
//导入mint-ui组件对象
import mintui from 'mint-ui';
//在Vue中全局使用mintui
Vue.use(mintui);

//注册mui的css样式
import '../statics/mui/css/mui.css';

//导入一个当前系统的全局基本样式
import '../statics/css/site.css';

//将vue-resource在vue中绑定,自动在vue对象实例上注入一个$http对象就可以使用ajax方法了
import vueResource from 'vue-resource';
Vue.use(vueResource);

//定义一个全局过滤器实现日期的格式化
import moment from 'moment';
Vue.filter('datefmt', function(input, fmtstring) {
  //使用momentjs这个日期格式化类库实现日期的格式化功能
  //input代表左值(原始时间格式),fmtstring代表右值括号内的规则
  return moment(input).format(fmtstring);
});

//使用图片预览组件vue-preview
import VuePreview from 'vue-preview';
Vue.use(VuePreview);

//利用Vue对象进行解析渲染
new Vue({
  el: '#app',
  //使用路由对象实例
  router: router1,
  render: c => c(App) //es6写法
})

 

View Code

 项目结构图:

www.weide1946.com 24

 

商品详情页开发(一)

步骤一:创建goodsinfo.vue文件

www.weide1946.com 25www.weide1946.com 26

<template>
  <div id="tml">
    商品详情
  </div>
</template>

<script>
</script>

<style>

</style>

www.weide1946.com,View Code

步骤二:修改goodslist.vue文件

www.weide1946.com 27www.weide1946.com 28

<template>
  <div id="tml">
    <!--利用mui中的图文表格组件实现-->
    <div id="mui-content" class="mui-content" style="background-color:#fff">
      <ul class="mui-table-view mui-grid-view">
        <li v-for="item in list" class="mui-table-view-cell mui-media mui-col-xs-6">
          <router-link v-bind="{to:'/goods/goodsinfo/' item.id}">
            <img class="mui-media-object" :src="item.img_url" style="height: 250px;">
            <div class="mui-media-body" v-text="item.title"></div>
            <div class="desc">
              <p>
                ¥{{item.sell_price}}
                <s>¥{{item.market_price}}</s>
              </p>
              <p>
                <h6 class="left">热卖中</h6>
                <h6 class="right">剩余{{item.stock_quantity}}件</h6>
              </p>
            </div>
          </router-link>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
  import { Toast } from 'mint-ui';
  // 代表vm
  export default {
    data() {
      return {
        list: []
      }
    },
    created() {
      this.getlist();
    },
    methods: {
      getlist() {
        //获取到商品列表数据
        var url = '../../../statics/json/goodslist.json';
        this.$http.get(url).then(function(res) {
          if(res.body.status != 0) {
            Toast(res.body.message);
            return;
          }
          //当服务器返回了正常数据的时候做赋值操作
          this.list = res.body.message;
        });
      }
    }
  }
</script>

<style scoped>
  #mui-content li {
    border: 1px solid rgba(0, 0, 0, 0.4);
    -webkit-box-shadow: 0 0 4px #000;
    -moz-box-shadow: 0 0 4px #000;
    box-shadow: 0 0 4px #000;
    margin-left: 4px;
    padding: 0px;
    background-color: #fff;
    margin-bottom: 6px;
  }  
  #mui-content .mui-media-body {
    color: #0094ff;
  } 
  #mui-content .desc {
    height: 60px;
    background-color: rgba(0, 0, 0, 0.2);
    margin-top: 10px;
    padding: 5px;
    text-align: left;
  } 
  #mui-content .desc span {
    color: #a22b2b;
    margin-right: 15px;
  }  
  #mui-content a {
    padding-left: 0px;
    margin-left: 0px;
  }  
  #mui-content .desc .right {
    position: absolute;
    right: 10px;
    bottom: 0px;
    font-weight: bold;
  }  
  #mui-content .desc .left {
    position: absolute;
    left: 10px;
    bottom: 0px;
    color: red;
    font-weight: bold;
  }
</style>

View Code

步骤三:配置入口文件mian.js的路由规则

www.weide1946.com 29www.weide1946.com 30

//导入vue核心包
import Vue from 'vue';

//导入App.vue的vue对象
import App from './App.vue';

//导入vue-router
import vueRouter from 'vue-router';

//将vueRouter对象绑定到Vue对象上
Vue.use(vueRouter);

//导入路由规则对应的组件对象
import home from './components/Home.vue';
import shopcar from './components/shopcar/car.vue';
import newslist from './components/news/newslist.vue';
import newsinfo from './components/news/newsinfo.vue';
import photolist from './components/photo/photolist.vue';
import photoinfo from './components/photo/photoinfo.vue';
import goodslist from './components/goods/goodslist.vue';
import goodsinfo from './components/goods/goodsinfo.vue';

//定义路由规则
var router1 = new vueRouter({
    //改变路由激活时的class名称
  linkActiveClass: 'mui-active', 
  routes: [{
      path: '/',
      component: home 
    }, {
      path: '/home',
      component: home
    },
    {
      path: '/shopcar',
      component: shopcar
    },
    {
      path: '/news/newslist',
      component: newslist
    },
    {
      path: '/news/newsinfo/:id',
      component: newsinfo
    },
    {
      path: '/photo/photolist',
      component: photolist
    },
    {
      path: '/photo/photoinfo/:id',
      component: photoinfo
    },
    {
      path: '/goods/goodslist',
      component: goodslist
    },
    {
      path: '/goods/goodsinfo/:id',
      component: goodsinfo
    }
  ]
});

//导入mint-ui的css文件
import 'mint-ui/lib/style.min.css';
//导入mint-ui组件对象
import mintui from 'mint-ui';
//在Vue中全局使用mintui
Vue.use(mintui);

//注册mui的css样式
import '../statics/mui/css/mui.css';

//导入一个当前系统的全局基本样式
import '../statics/css/site.css';

//将vue-resource在vue中绑定,自动在vue对象实例上注入一个$http对象就可以使用ajax方法了
import vueResource from 'vue-resource';
Vue.use(vueResource);

//定义一个全局过滤器实现日期的格式化
import moment from 'moment';
Vue.filter('datefmt', function(input, fmtstring) {
  //使用momentjs这个日期格式化类库实现日期的格式化功能
  //input代表左值(原始时间格式),fmtstring代表右值括号内的规则
  return moment(input).format(fmtstring);
});

//使用图片预览组件vue-preview
import VuePreview from 'vue-preview';
Vue.use(VuePreview);

//利用Vue对象进行解析渲染
new Vue({
  el: '#app',
  //使用路由对象实例
  router: router1,
  render: c => c(App) //es6写法
})

View Code

 

案例四(商品详情页轮播图实现)

步骤一:在subcom文件夹中封装一个公用轮播组件slider.vue

www.weide1946.com 31www.weide1946.com 32

<template>
  <div id="tml">
    <mt-swipe :auto="2000">
      <mt-swipe-item v-for="item in imgs">
        <img :src="item.img">
      </mt-swipe-item>
    </mt-swipe>
  </div>
</template>

<script>
  export default {
    //用来接收父组件传入过来的数据
    props: ['imgs']
  }
</script>

<style scoped>
  /*重写轮播图样式*/

  .mint-swipe {
    height: 310px;
  }
  .mint-swipe-item {
    width: 100%;
    height: 300px;
  }
  .mint-swipe-item img {
    width: 100%;
    height: 80%;
  }
</style>

View Code

此时Home.vue的代码为

www.weide1946.com 33www.weide1946.com 34

<template>
  <div id="tml">
      <!--使用组件结合mint-ui实现轮播图-->
    <silder :imgs="list"></silder>

    <!--使用MUI的九宫格-->
    <div class="mui-content">
      <ul class="mui-table-view mui-grid-view mui-grid-9">
        <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
          <router-link to="/news/newslist">

            <div class="mui-media-body">新闻资讯</div>
          </router-link>
        </li>
        <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
          <router-link to="/photo/photolist">

            <div class="mui-media-body">图片分享</div>
          </router-link>
        </li>
        <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
          <router-link to="/goods/goodslist">

            <div class="mui-media-body">商品购买</div>
          </router-link>
        </li>
        <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
          <router-link to="/feedback">

            <div class="mui-media-body">留言反馈</div>
          </router-link>
        </li>
        <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
          <router-link to="/vide">

            <div class="mui-media-body">视频专区</div>
          </router-link>
        </li>
        <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
          <router-link to="/callme">

            <div class="mui-media-body">联系我们</div>
          </router-link>
        </li>
      </ul>
    </div>

  </div>
</template>

<script>
  import { Toast } from 'mint-ui';
  import silder from './subcom/slider.vue';

  export default {
    components: {
      silder
    },
    data() {
      return {
        list: []
      }
    },
    created() {
      // 当页面中的data和methods对象都创建完毕以后,就会自动调用created
      this.getimgs();
    },
    methods: {
      getimgs() {
        // 实现轮播组件中的数据请求
        // 1.0 确定url
        var url = '../../statics/json/homeslide.json'
        console.log(url);
        // 2.0 调用$http.get()
        this.$http.get(url).then(function(response) {
          var data = response.body;
          //错误处理
          if(data.status != 0) {
            Toast(data.message);
            return;
          }
          // 如果服务器返回的数据正常则赋值给list
          this.list = data.message;
        });
      }
    }
  }
</script>

<style scoped>
  /*重写九宫格样式*/  
  .mui-content,
  .mui-content ul li a {
    background: #fff;
  }
  /*改变九宫格图标样式*/ 
  .mui-grid-9 .mui-icon-home:before,
  .mui-grid-9 .mui-icon-email:before,
  .mui-grid-9 .mui-icon-chatbubble:before,
  .mui-grid-9 .mui-icon-location:before,
  .mui-grid-9 .mui-icon-search:before,
  .mui-grid-9 .mui-icon-phone:before {
    content: '';
    display: inline-block;
    width: 50px;
    height: 50px;
    background-repeat: round;
  }
  .mui-grid-9 .mui-icon-home:before {
    background-image: url(../../statics/imgs/Hgrid/1.png);
  }
  .mui-grid-9 .mui-icon-email:before {
    background-image: url(../../statics/imgs/Hgrid/2.png);
  }
  .mui-grid-9 .mui-icon-chatbubble:before {
    background-image: url(../../statics/imgs/Hgrid/3.png);
  }
  .mui-grid-9 .mui-icon-location:before {
    background-image: url(../../statics/imgs/Hgrid/4.png);
  }
  .mui-grid-9 .mui-icon-search:before {
    background-image: url(../../statics/imgs/Hgrid/5.png);
  }
  .mui-grid-9 .mui-icon-phone:before {
    background-image: url(../../statics/imgs/Hgrid/6.png);
  }
</style>

View Code

步骤二:创建goodslunbo1.json和goodslunbo.json用来存放轮播图片

www.weide1946.com 35www.weide1946.com 36

{
  "status": 0,
  "message": [
    {
      "src": "../../statics/imgs/goodsinfo/lunbo01.jpg",
      "url": "#",
      "img": "../../statics/imgs/goodsinfo/lunbo01.jpg"
    }, {
      "src": "../../statics/imgs/goodsinfo/lunbo02.jpg",
      "url": "#",
      "img": "../../statics/imgs/goodsinfo/lunbo02.jpg"
    }, {
      "src": "../../statics/imgs/goodsinfo/lunbo03.jpg",
      "url": "#",
      "img": "../../statics/imgs/goodsinfo/lunbo03.jpg"
    }
  ]
}

View Code

www.weide1946.com 37www.weide1946.com 38

{
  "status": 0,
  "message": [
    {
      "src": "../../statics/imgs/goodsinfo/lunbo04.jpg",
      "url": "#",
      "img": "../../statics/imgs/goodsinfo/lunbo04.jpg"
    }, {
      "src": "../../statics/imgs/goodsinfo/lunbo05.jpg",
      "url": "#",
      "img": "../../statics/imgs/goodsinfo/lunbo05.jpg"
    }, {
      "src": "../../statics/imgs/goodsinfo/lunbo06.jpg",
      "url": "#",
      "img": "../../statics/imgs/goodsinfo/lunbo06.jpg"
    }
  ]
}

View Code

步骤三:修改goodsinfo.vue文件

www.weide1946.com 39www.weide1946.com 40

<template>
  <div id="tml">
    <!--1.0 商品轮播图-->
    <silder :imgs="imgs"></silder>

    <!--2.0 实现商品购买区-->

    <!--3.0 图文详情-->

    <!--4.0 商品评论-->
  </div>
</template>

<script>
  import silder from '../subcom/slider.vue';

  export default {
    components: {
      silder
    },
    data() {
      return {
        id: 0, //表示商品id
        imgs: []
      }
    },
    created() {
      //获取url传入的商品id值
      this.id = this.$route.params.id;
      this.getimgs();
    },
    methods: {
      getimgs() {
        var url = '../../../statics/json/goodslunbo'   this.id   '.json';
        this.$http.get(url).then(function(res) {
          if(res.body.status != 0) {
            Toast(res.body.message);
            return;
          }
          //当服务器返回了正常数据的时候做赋值操作
          this.imgs = res.body.message;
        });
      }
    }
  }
</script>

<style scoped>

</style>

View Code

 

实现商品购买区

步骤一:修改goodsinfo.vue文件

www.weide1946.com 41www.weide1946.com 42

<template>
  <div id="tml">
    <!--1.0 商品轮播图-->
    <div class="silder">
      <silder :imgs="imgs"></silder>
    </div>

    <!--2.0 实现商品购买区-->
    <div id="buy">
      <h4 v-text="info.title"></h4>
      <p class="line"></p>
      <ul>
        <li class="price">
          市场价: <s>¥{{info.market_price}}</s> 销售价:¥{{info.sell_price}}
        </li>
        <li>
          购买数量:
        </li>
        <li>
          <mt-button type="primary" size="small">立即购买</mt-button>
          <mt-button type="danger" size="small">加入购物车</mt-button>
        </li>
      </ul>
    </div>

    <div id="params">
      <h6>商品参数</h6>
      <p class="line"></p>
      <ul>
        <li>商品货号:{{info.goods_no}}</li>
        <li>库存情况:{{info.stock_quantity}}</li>
        <li>上架时间:{{info.add_time}}</li>
      </ul>
    </div>

    <!--3.0 图文详情-->
    <!--4.0 商品评论-->
    <div id="other">
      <mt-button plain class="imgdesc" type="primary" size="large">图文详情</mt-button>
      <mt-button plain type="danger" size="large">商品评论</mt-button>
    </div>
  </div>
</template>

<script>
  import silder from '../subcom/slider.vue';

  export default {
    components: {
      silder
    },
    data() {
      return {
        id: 0, //表示商品id
        imgs: [],
        info: {} //存储商品详细信息
      }
    },
    created() {
      //获取url传入的商品id值
      this.id = this.$route.params.id;
      this.getimgs();
      this.getinfo();
    },
    methods: {
      getimgs() {
        var url = '../../../statics/json/goodslunbo'   this.id   '.json';
        this.$http.get(url).then(function(res) {
          //判断状态
          this.imgs = res.body.message;
        });
      },
      getinfo() {
        var url = '../../../statics/json/goodslist.json';
        this.$http.get(url).then(function(res) {
          var body = res.body;
          if(body.status != 0) {
            alert(body.message);
            return;
          }

          for(var i = 0; i < body.message.length; i  ) {
            if(this.id == body.message[i].id) {
              console.log(body.message[i])
              this.info = body.message[i];
              console.log(this.info);
            }
          }
        });
      }

    }
  }
</script>

<style scoped>
  .silder {
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
    margin: 5px;
  }

  #buy,
  #params,
  #other {
    margin: 5px;
    padding: 5px;
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
  }

  .line {
    height: 1px;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }

  #buy ul,
  #params ul {
    padding-left: 0px;
  }

  #buy h4 {
    color: #0094ff;
    padding: 5px;
  }

  #buy li,
  #params li {
    list-style: none;
    padding: 8px;
  }

  #buy .price span {
    color: red;
  }

  #other .imgdesc {
    margin-bottom: 20px;
  }
</style>

View Code

步骤二:创建goodslist.json文件

www.weide1946.com 43www.weide1946.com 44

{
  "status": 0,
  "message": [
    {
      "id": 1,
      "title": "动漫被套床单",
      "add_time": "2017-12-25",
      "zhaiyao": "尺寸图样皆可以订制,如果在店铺展示页面没有喜欢的角色,可以咨询客服,查看图库,进行选取!",
      "click": 30,
      "img_url": "../../statics/imgs/goodslist/goodslist01.jpg",
      "sell_price": 78,
      "market_price": 68,
      "stock_quantity": 200,
      "goods_no": "SD13313123"
    }, {
      "id": 2,
      "title": "二次元毛绒抱枕",
      "add_time": "2017-12-25",
      "zhaiyao": "此优惠限5件,超出则该商品全部恢复非活动价",
      "click": 33,
      "img_url": "../../statics/imgs/goodslist/goodslist02.jpg",
      "sell_price": 58,
      "market_price": 63,
      "stock_quantity": 500,
      "goods_no": "SD13313123"
    }, {
      "id": 3,
      "title": "逍遥宅品猫咪痛包",
      "add_time": "2017-12-25",
      "zhaiyao": "一共是一个外包 印花猫咪内包 纯色内包 肩带 手拎带。自由发挥自主搭配!带子之后会换成皮的!",
      "click": 34,
      "img_url": "../../statics/imgs/goodslist/goodslist03.jpg",
      "sell_price": 57,
      "market_price": 63,
      "stock_quantity": 500,
      "goods_no": "SD13313123"
    }, {
      "id": 4,
      "title": "动漫周边保温杯",
      "add_time": "2017-12-25",
      "zhaiyao": "采用304不锈钢 双层真空内胆 保温久不烫手 支持来图定制 买就送杯套",
      "click": 36,
      "img_url": "../../statics/imgs/goodslist/goodslist04.jpg",
      "sell_price": 80,
      "market_price": 100,
      "stock_quantity": 300,
      "goods_no": "SD13313123"
    }, {
      "id": 5,
      "title": "雪初音卫衣棉服",
      "add_time": "2017-12-25",
      "zhaiyao": "此优惠限5件,超出则该商品全部恢复非活动价",
      "click": 63,
      "img_url": "../../statics/imgs/goodslist/goodslist05.jpg",
      "sell_price": 66,
      "market_price": 80,
      "stock_quantity": 300,
      "goods_no": "SD13313123"
    }, {
      "id": 6,
      "title": "Monchhichi萌趣趣",
      "add_time": "2017-12-25",
      "zhaiyao": "Monchhichi萌趣趣十二生肖狗鸡小兔马羊龙老虎猪小鸡公仔送人礼品",
      "click": 38,
      "img_url": "../../statics/imgs/goodslist/goodslist06.jpg",
      "sell_price": 75,
      "market_price": 90,
      "stock_quantity": 800,
      "goods_no": "SD13313123"
    }
  ]
}

View Code

 

实现商品图文详情

步骤一:创建一个goodsdesc.json文件

www.weide1946.com 45www.weide1946.com 46

{
  "status": 0,
  "message": [
    {
      "id": 1,
      "title": "动漫被套床单",
      "content": "尺寸图样皆可以订制,如果在店铺展示页面没有喜欢的角色,可以咨询客服,查看图库,进行选取!"
    }, {
      "id": 2,
      "title": "二次元毛绒抱枕",
      "content": "此优惠限5件,超出则该商品全部恢复非活动价"
    }
  ]
}

View Code

步骤二:创建goodsdesc.vue文件

www.weide1946.com 47www.weide1946.com 48

<template>
  <div id="tml">
    <h4 v-text="info.title" style="padding-top: 10px;"></h4>
    <p class="line"></p>
    <p v-html="info.content"></p>
  </div>
</template>

<script>
  import { Toast } from 'mint-ui';
  export default {
    data() {
      return {
        id: 0, // 代表的是当前商品的id
        info: {}
      }
    },
    created() {
      this.id = this.$route.params.id;
      this.getinfo();
    },
    methods: {
      getinfo() {
        //1.0 定义url
        var url = '../../../statics/json/goodsdesc.json';
        //2.0 发出ajax请求获取数据
        this.$http.get(url).then(function (res) {
          var body = res.body;
          if (body.status != 0) {
            alert(body.message);
            return;
          }
          //3.0 赋值
          for (var i = 0; i < body.message.length; i  ) {
            if (this.id == body.message[i].id) {
              console.log(body.message[i])
              this.info = body.message[i];
              console.log(this.info);
            }
          }
        });
      }
    }
  }
</script>

<style scoped>
  #tmpl {
    padding: 5px;
    margin-top: 60px;
  }
  #tmpl h4 {
    color: #0094ff;
  }
  #tmpl .line {
    height: 1px;
    border: 1px solid rgba(0, 0, 0, 0.3);
  }
</style>

View Code

步骤三:修改goodsinfo.vue文件

www.weide1946.com 49www.weide1946.com 50

<template>
  <div id="tml">
    <!--1.0 商品轮播图-->
    <div class="silder">
      <silder :imgs="imgs"></silder>
    </div>

    <!--2.0 实现商品购买区-->
    <div id="buy">
      <h4 v-text="info.title"></h4>
      <p class="line"></p>
      <ul>
        <li class="price">
          市场价: <s>¥{{info.market_price}}</s> 销售价:¥{{info.sell_price}}
        </li>
        <li>
          购买数量:
        </li>
        <li>
          <mt-button type="primary" size="small">立即购买</mt-button>
          <mt-button type="danger" size="small">加入购物车</mt-button>
        </li>
      </ul>
    </div>

    <div id="params">
      <h6>商品参数</h6>
      <p class="line"></p>
      <ul>
        <li>商品货号:{{info.goods_no}}</li>
        <li>库存情况:{{info.stock_quantity}}</li>
        <li>上架时间:{{info.add_time}}</li>
      </ul>
    </div>

    <!--3.0 图文详情-->
    <!--4.0 商品评论-->
    <div id="other">
      <router-link v-bind="{to:'/goods/goodsdesc/' id}">
            <mt-button class="imgdesc" type="primary" size="large">图文详情</mt-button>
            </router-link>
            <mt-button type="danger" size="large">商品评论</mt-button>
    </div>
  </div>
</template>

<script>
  import silder from '../subcom/slider.vue';

  export default {
    components: {
      silder
    },
    data() {
      return {
        id: 0, //表示商品id
        imgs: [],
        info: {} //存储商品详细信息
      }
    },
    created() {
      //获取url传入的商品id值
      this.id = this.$route.params.id;
      this.getimgs();
      this.getinfo();
    },
    methods: {
      getimgs() {
        var url = '../../../statics/json/goodslunbo'   this.id   '.json';
        this.$http.get(url).then(function(res) {
          //判断状态
          this.imgs = res.body.message;
        });
      },
      getinfo() {
        var url = '../../../statics/json/goodslist.json';
        this.$http.get(url).then(function(res) {
          var body = res.body;
          if(body.status != 0) {
            alert(body.message);
            return;
          }

          for(var i = 0; i < body.message.length; i  ) {
            if(this.id == body.message[i].id) {
              this.info = body.message[i];
            }
          }
        });
      }

    }
  }
</script>

<style scoped>
  .silder {
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
    margin: 5px;
  }  
  #buy,
  #params,
  #other {
    margin: 5px;
    padding: 5px;
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
  } 
  .line {
    height: 1px;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }  
  #buy ul,
  #params ul {
    padding-left: 0px;
  }  
  #buy h4 {
    color: #0094ff;
    padding: 5px;
  } 
  #buy li,
  #params li {
    list-style: none;
    padding: 8px;
  }  
  #buy .price span {
    color: red;
  }  
  #other .imgdesc {
    margin-bottom: 20px;
  }
</style>

View Code

步骤四:配置入口文件main.js的路由规则

www.weide1946.com 51www.weide1946.com 52

//导入vue核心包
import Vue from 'vue';

//导入App.vue的vue对象
import App from './App.vue';

//导入vue-router
import vueRouter from 'vue-router';
//将vueRouter对象绑定到Vue对象上
Vue.use(vueRouter);

//使用图片预览组件vue-preview
import VuePreview from 'vue-preview';
Vue.use(VuePreview);

//导入mint-ui的css文件
import 'mint-ui/lib/style.min.css';
//导入mint-ui组件对象
import mintui from 'mint-ui';
//在Vue中全局使用mintui
Vue.use(mintui);

//注册mui的css样式
import '../statics/mui/css/mui.css';

//导入一个当前系统的全局基本样式
import '../statics/css/site.css';

//将vue-resource在vue中绑定,自动在vue对象实例上注入一个$http对象就可以使用ajax方法了
import vueResource from 'vue-resource';
Vue.use(vueResource);

//导入路由规则对应的组件对象
import home from './components/Home.vue';
import shopcar from './components/shopcar/car.vue';
import newslist from './components/news/newslist.vue';
import newsinfo from './components/news/newsinfo.vue';
import photolist from './components/photo/photolist.vue';
import photoinfo from './components/photo/photoinfo.vue';
import goodslist from './components/goods/goodslist.vue';
import goodsinfo from './components/goods/goodsinfo.vue';
import goodsdesc from './components/goods/goodsdesc.vue';

//定义路由规则
var router1 = new vueRouter({
    //改变路由激活时的class名称
  linkActiveClass: 'mui-active', 
  routes: [{
      path: '/',
      component: home 
    }, {
      path: '/home',
      component: home
    },
    {
      path: '/shopcar',
      component: shopcar
    },
    {
      path: '/news/newslist',
      component: newslist
    },
    {
      path: '/news/newsinfo/:id',
      component: newsinfo
    },
    {
      path: '/photo/photolist',
      component: photolist
    },
    {
      path: '/photo/photoinfo/:id',
      component: photoinfo
    },
    {
      path: '/goods/goodslist',
      component: goodslist
    },
    {
      path: '/goods/goodsinfo/:id',
      component: goodsinfo
    },
    {
      path: '/goods/goodsdesc/:id',
      component: goodsdesc
    }
  ]
});

//定义一个全局过滤器实现日期的格式化
import moment from 'moment';
Vue.filter('datefmt', function(input, fmtstring) {
  //使用momentjs这个日期格式化类库实现日期的格式化功能
  //input代表左值(原始时间格式),fmtstring代表右值括号内的规则
  return moment(input).format(fmtstring);
});

//利用Vue对象进行解析渲染
new Vue({
  el: '#app',
  //使用路由对象实例
  router: router1,
  render: c => c(App) //es6写法
})

View Code

 

实现购买功能区

步骤一:创建一个组件inputNumber.vue

www.weide1946.com 53www.weide1946.com 54

<template>
  <div id="subtmpl">
    <div class="inleft div" @click="substrict">-</div>
    <div class="incenter div" v-text="count"></div>
    <div class="inright div" @click="add"> </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        count: 1 //代表购买商品的数量
      }
    },
    methods: {
      substrict() {
        this.count--;
        //                确保最小值为1
        if(this.count < 1) {
          this.count = 1;
        }
        this.sendmessage();
      },
      add() {
        this.count  ;
        this.sendmessage();
      },
      sendmessage() {
        this.$emit('dataobj', this.count);
      }
    }
  }
</script>

<style scoped>
  #subtmpl .div {
    width: 40px;
    height: 25px;
    line-height: 25px;
    border: 1px solid #000;
    display: inline-block;
    text-align: center;
  }
</style>

View Code

步骤二:修改goodsinfo.vue文件

www.weide1946.com 55www.weide1946.com 56

<template>
  <div id="tml">
    <!--1.0 商品轮播图-->
    <div class="silder">
      <silder :imgs="imgs"></silder>
    </div>

    <!--2.0 实现商品购买区-->
    <div id="buy">
      <h4 v-text="info.title"></h4>
      <p class="line"></p>
      <ul>
        <li class="price">
          市场价: <s>¥{{info.market_price}}</s> 销售价:¥{{info.sell_price}}
        </li>
        <li>
          <li class="inputli">
            购买数量:
            <inputnumber v-on:dataobj="getcount" class="inputnumber"></inputnumber>
          </li>
        </li>
        <li>
          <mt-button type="primary" size="small">立即购买</mt-button>
          <mt-button type="danger" size="small">加入购物车</mt-button>
        </li>
      </ul>
    </div>

    <div id="params">
      <h6>商品参数</h6>
      <p class="line"></p>
      <ul>
        <li>商品货号:{{info.goods_no}}</li>
        <li>库存情况:{{info.stock_quantity}}</li>
        <li>上架时间:{{info.add_time}}</li>
      </ul>
    </div>

    <!--3.0 图文详情-->
    <!--4.0 商品评论-->
    <div id="other">
      <router-link v-bind="{to:'/goods/goodsdesc/' id}">
        <mt-button class="imgdesc" type="primary" size="large">图文详情</mt-button>
      </router-link>
      <mt-button type="danger" size="large">商品评论</mt-button>
    </div>
  </div>
</template>

<script>
  import silder from '../subcom/slider.vue';
  import inputnumber from '../subcom/inputNumber.vue';
  export default {
    components: {
      silder,
      inputnumber
    },
    data() {
      return {
        inputNumberCount: 1, //表示当前购买商品的数量
        id: 0, //表示商品id
        imgs: [],
        info: {} //存储商品详细信息
      }
    },
    created() {
      //获取url传入的商品id值
      this.id = this.$route.params.id;
      this.getimgs();
      this.getinfo();
    },
    methods: {
      //获取inputnumber组件中传入的值
      getcount(count) {
        this.inputNumberCount = count;
        console.log(count);
      },
      getimgs() {
        var url = '../../json/goodslunbo'   this.id   '.json';
        this.$http.get(url).then(function(res) {
          //判断状态
          this.imgs = res.body.message;
        });
      },
      getinfo() {
        var url = '../../json/goodslist.json';
        this.$http.get(url).then(function(res) {
          var body = res.body;
          if(body.status != 0) {
            alert(body.message);
            return;
          }

          for(var i = 0; i < body.message.length; i  ) {
            if(this.id == body.message[i].id) {
              console.log(body.message[i])
              this.info = body.message[i];
              console.log(this.info);
            }
          }
        });
      }

    }
  }
</script>

<style scoped>
  .silder {
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
    margin: 5px;
  }

  #buy,
  #params,
  #other {
    margin: 5px;
    padding: 5px;
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
  }

  .line {
    height: 1px;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }

  #buy ul,
  #params ul {
    padding-left: 0px;
  }

  #buy h4 {
    color: #0094ff;
    padding: 5px;
  }

  #buy li,
  #params li {
    list-style: none;
    padding: 8px;
  }

  #buy .price span {
    color: red;
  }

  #other .imgdesc {
    margin-bottom: 20px;
  }

  .inputli {
    position: relative;
  }

  .inputnumber {
    position: absolute;
    left: 100px;
    top: 5px;
  }
</style>

View Code

 

将底部的购物车图标中数字叠加

步骤一:涉及到三个页面的通信,因此需要创建一个共同的Vue对象。

vm.js

import Vue from 'Vue';

export const COUNTSTR = 'inputNumberCount';
export var vm = new Vue();

步骤二:修改根组件App.vue

www.weide1946.com 57www.weide1946.com 58

<!--以后项目的根组件-->
<template>
  <div>
    <!--1.0利用mint-ui中的header组件实现整个系统的头部-->
    <mt-header fixed title="hello"></mt-header>

    <!--2.0利用vue-router的<router-view></router-view>进行占位-->
    <router-view></router-view>

    <!--3.0利用mui中的tabbar组件实现系统的底部-->
    <nav class="mui-bar mui-bar-tab">
      <router-link class="mui-tab-item" to="/home">

        首页
      </router-link>
      <router-link class="mui-tab-item" to="#tabbar-with-chat">

        会员
      </router-link>
      <router-link class="mui-tab-item" to="/shopcar">
        0
        购物车
      </router-link>
      <router-link class="mui-tab-item" to="/tabbar-with-map">

        搜索
      </router-link>
    </nav>
  </div>
</template>

<script>
  import { vm, COUNTSTR } from './kits/vm.js';
  // 利用 vm.$on() 来注册 COUNT这个常量代表的事件
  vm.$on(COUNTSTR, function(count) {
    //1.0 将count值追加到购物车中
    var badgeobj = document.querySelector('#badge');
    badgeobj.innerText = parseInt(badgeobj.innerText)   count;
  });

  // 2.0负责导出.vue这个组件对象,它本质上是一个Vue对象
  // 所以Vue中该定义的元素都可以使用
  export default { // es6的导出对象的写法
    data() { //等价于 es5的 data:function(){
      return {

      }
    },
    methods: {

    },
    created() {

    }
  }
</script>

<style scoped>
  /* 3.0当前页面的CSS样式写到这里,其中scoped表示这个里面
      写的CSS代码知识在当前组件页面上有效,不会影响到其他组件页面
     * */
</style>

View Code

步骤三:修改goodsinfo.vue文件

www.weide1946.com 59www.weide1946.com 60

<template>
  <div id="tml">
    <!--1.0 商品轮播图-->
    <div class="silder">
      <silder :imgs="imgs"></silder>
    </div>

    <!--2.0 实现商品购买区-->
    <div id="buy">
      <h4 v-text="info.title"></h4>
      <p class="line"></p>
      <ul>
        <li class="price">
          市场价: <s>¥{{info.market_price}}</s> 销售价:¥{{info.sell_price}}
        </li>
        <li>
          <li class="inputli">
            购买数量:
            <inputnumber v-on:dataobj="getcount" class="inputnumber"></inputnumber>
          </li>
        </li>
        <li>
          <mt-button type="primary" size="small">立即购买</mt-button>
          <mt-button type="danger" size="small" @click="toshopcar">加入购物车</mt-button>
        </li>
      </ul>
    </div>

    <div id="params">
      <h6>商品参数</h6>
      <p class="line"></p>
      <ul>
        <li>商品货号:{{info.goods_no}}</li>
        <li>库存情况:{{info.stock_quantity}}</li>
        <li>上架时间:{{info.add_time}}</li>
      </ul>
    </div>

    <!--3.0 图文详情-->
    <!--4.0 商品评论-->
    <div id="other">
      <router-link v-bind="{to:'/goods/goodsdesc/' id}">
        <mt-button class="imgdesc" type="primary" size="large">图文详情</mt-button>
      </router-link>
      <mt-button type="danger" size="large">商品评论</mt-button>
    </div>
  </div>
</template>

<script>
  import silder from '../subcom/slider.vue';
  import inputnumber from '../subcom/inputNumber.vue';
  //使用vm对象
  import { vm, COUNTSTR } from '../../kits/vm.js';
  export default {
    components: {
      silder,
      inputnumber
    },
    data() {
      return {
        inputNumberCount: 1, //表示当前购买商品的数量
        id: 0, //表示商品id
        imgs: [],
        info: {} //存储商品详细信息
      }
    },
    created() {
      //获取url传入的商品id值
      this.id = this.$route.params.id;
      this.getimgs();
      this.getinfo();
    },
    methods: {
      //加入购物车方法
      toshopcar() {
        //触发事件
        vm.$emit(COUNTSTR, this.inputNumberCount);
      },

      //获取inputnumber组件中传入的值
      getcount(count) {
        this.inputNumberCount = count;
        console.log(count);
      },
      getimgs() {
        var url = '../../json/goodslunbo'   this.id   '.json';
        this.$http.get(url).then(function(res) {
          //判断状态
          this.imgs = res.body.message;
        });
      },
      getinfo() {
        var url = '../../json/goodslist.json';
        this.$http.get(url).then(function(res) {
          var body = res.body;
          if(body.status != 0) {
            alert(body.message);
            return;
          }

          for(var i = 0; i < body.message.length; i  ) {
            if(this.id == body.message[i].id) {
              console.log(body.message[i])
              this.info = body.message[i];
              console.log(this.info);
            }
          }
        });
      }

    }
  }
</script>

<style scoped>
  .silder {
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
    margin: 5px;
  }

  #buy,
  #params,
  #other {
    margin: 5px;
    padding: 5px;
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
  }

  .line {
    height: 1px;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }

  #buy ul,
  #params ul {
    padding-left: 0px;
  }

  #buy h4 {
    color: #0094ff;
    padding: 5px;
  }

  #buy li,
  #params li {
    list-style: none;
    padding: 8px;
  }

  #buy .price span {
    color: red;
  }

  #other .imgdesc {
    margin-bottom: 20px;
  }

  .inputli {
    position: relative;
  }

  .inputnumber {
    position: absolute;
    left: 100px;
    top: 5px;
  }
</style>

View Code

项目结构:

www.weide1946.com 61

 

本地存储购物数据

步骤一:创建一个负责操作localStorage的js文件

www.weide1946.com 62www.weide1946.com 63

localSg.js

// 负责操作localStorage的文件
/*
 *  获取数据:var Str  =localStorage.getItem(key);
 *  添加和追加数据: localStorage.setItem(key,value) ,value 是一个字符串
 *  移除数据 : localStorage.removeItem(key);
 * */

// 1.0 定义常量key,将来操作的localStorage中的数据都以这个key来作为标识
export const KEY = 'goodsdata';
export var valueObj = {
  goodsid: 0,
  count: 0
};

// 2.0 实现数据的增加
// value;格式: {goodsid:87,count:10}
export function setItem(value) {
  //1.0 获取json格式
  var jsonString = localStorage.getItem(KEY);
  jsonString = jsonString || '[]';
  var arr = JSON.parse(jsonString);
  // 2.0 将value追加进入arr
  arr.push(value);
  // 3.0 将arr 转换成json字符串保存起来
  localStorage.setItem(KEY, JSON.stringify(arr));
}

// 3.0 获取数据
export function getItem() {
  var jsonString = localStorage.getItem(KEY);
  //将json格式字符串转换成 js对象
  // jsonString:是一个标准的json格式
  jsonString = jsonString || '[]';

  return JSON.parse(jsonString);
}

// 4.0 移除数据
export function remoteItem() {

}

View Code

步骤二:修改goodsinfo.vue文件

www.weide1946.com 64www.weide1946.com 65

<template>
  <div id="tml">
    <!--1.0 商品轮播图-->
    <div class="silder">
      <silder :imgs="imgs"></silder>
    </div>

    <!--2.0 实现商品购买区-->
    <div id="buy">
      <h4 v-text="info.title"></h4>
      <p class="line"></p>
      <ul>
        <li class="price">
          市场价: <s>¥{{info.market_price}}</s> 销售价:¥{{info.sell_price}}
        </li>
        <li>
          <li class="inputli">
            购买数量:
            <inputnumber v-on:dataobj="getcount" class="inputnumber"></inputnumber>
          </li>
        </li>
        <li>
          <mt-button type="primary" size="small">立即购买</mt-button>
          <mt-button type="danger" size="small" @click="toshopcar">加入购物车</mt-button>
        </li>
      </ul>
    </div>

    <div id="params">
      <h6>商品参数</h6>
      <p class="line"></p>
      <ul>
        <li>商品货号:{{info.goods_no}}</li>
        <li>库存情况:{{info.stock_quantity}}</li>
        <li>上架时间:{{info.add_time}}</li>
      </ul>
    </div>

    <!--3.0 图文详情-->
    <!--4.0 商品评论-->
    <div id="other">
      <router-link v-bind="{to:'/goods/goodsdesc/' id}">
        <mt-button class="imgdesc" type="primary" size="large">图文详情</mt-button>
      </router-link>
      <mt-button type="danger" size="large">商品评论</mt-button>
    </div>
  </div>
</template>

<script>
  import silder from '../subcom/slider.vue';
  import inputnumber from '../subcom/inputNumber.vue';
  //使用vm对象
  import { vm, COUNTSTR } from '../../kits/vm.js';
  import {setItem,valueObj} from '../../kits/localSg.js';
  export default {
    components: {
      silder,
      inputnumber
    },
    data() {
      return {
        inputNumberCount: 1, //表示当前购买商品的数量
        id: 0, //表示商品id
        imgs: [],
        info: {} //存储商品详细信息
      }
    },
    created() {
      //获取url传入的商品id值
      this.id = this.$route.params.id;
      this.getimgs();
      this.getinfo();
    },
    methods: {
      //加入购物车方法
      toshopcar() {
        //触发事件
        vm.$emit(COUNTSTR, this.inputNumberCount);
        //2.0 将数据保存到localStroage中
                valueObj.goodsid = this.id;
                valueObj.count = this.inputNumberCount;
                setItem(valueObj);
      },

      //获取inputnumber组件中传入的值
      getcount(count) {
        this.inputNumberCount = count;
        console.log(count);
      },
      getimgs() {
        var url = '../../json/goodslunbo'   this.id   '.json';
        this.$http.get(url).then(function(res) {
          //判断状态
          this.imgs = res.body.message;
        });
      },
      getinfo() {
        var url = '../../json/goodslist.json';
        this.$http.get(url).then(function(res) {
          var body = res.body;
          if(body.status != 0) {
            alert(body.message);
            return;
          }

          for(var i = 0; i < body.message.length; i  ) {
            if(this.id == body.message[i].id) {
              console.log(body.message[i])
              this.info = body.message[i];
              console.log(this.info);
            }
          }
        });
      }

    }
  }
</script>

<style scoped>
  .silder {
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
    margin: 5px;
  }

  #buy,
  #params,
  #other {
    margin: 5px;
    padding: 5px;
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
  }

  .line {
    height: 1px;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }

  #buy ul,
  #params ul {
    padding-left: 0px;
  }

  #buy h4 {
    color: #0094ff;
    padding: 5px;
  }

  #buy li,
  #params li {
    list-style: none;
    padding: 8px;
  }

  #buy .price span {
    color: red;
  }

  #other .imgdesc {
    margin-bottom: 20px;
  }

  .inputli {
    position: relative;
  }

  .inputnumber {
    position: absolute;
    left: 100px;
    top: 5px;
  }
</style>

View Code

 

实现加入购物车动态效果

www.weide1946.com 66www.weide1946.com 67

<template>
  <div id="tml">
    <!--1.0 商品轮播图-->
    <div class="silder">
      <silder :imgs="imgs"></silder>
    </div>

    <!--2.0 实现商品购买区-->
    <div id="buy">
      <h4 v-text="info.title"></h4>
      <p class="line"></p>
      <ul>
        <li class="price">
          市场价: <s>¥{{info.market_price}}</s> 销售价:¥{{info.sell_price}}
        </li>
        <li class="inputli">
          购买数量:
          <inputnumber v-on:dataobj="getcount" class="inputnumber"></inputnumber>
          <transition name="show" @before-enter="beforeEnter" @enter="enter" @after-enter="afterEnter">
            <div v-if="isshow" class="ball"></div>
          </transition>
        </li>
        <li>
          <mt-button type="primary" size="small">立即购买</mt-button>
          <mt-button type="danger" size="small" @click="toshopcar">加入购物车</mt-button>
        </li>
      </ul>
    </div>

    <div id="params">
      <h6>商品参数</h6>
      <p class="line"></p>
      <ul>
        <li>商品货号:{{info.goods_no}}</li>
        <li>库存情况:{{info.stock_quantity}}</li>
        <li>上架时间:{{info.add_time}}</li>
      </ul>
    </div>

    <!--3.0 图文详情-->
    <!--4.0 商品评论-->
    <div id="other">
      <router-link v-bind="{to:'/goods/goodsdesc/' id}">
        <mt-button class="imgdesc" type="primary" size="large">图文详情</mt-button>
      </router-link>
      <mt-button type="danger" size="large">商品评论</mt-button>
    </div>
  </div>
</template>

<script>
  import silder from '../subcom/slider.vue';
  import inputnumber from '../subcom/inputNumber.vue';
  //使用vm对象
  import { vm, COUNTSTR } from '../../kits/vm.js';
  import { setItem, valueObj } from '../../kits/localSg.js';
  export default {
    components: {
      silder,
      inputnumber
    },
    data() {
      return {
        isshow: false, //控制小球的显示状态
        inputNumberCount: 1, //表示当前购买商品的数量
        id: 0, //表示商品id
        imgs: [],
        info: {} //存储商品详细信息
      }
    },
    created() {
      //获取url传入的商品id值
      this.id = this.$route.params.id;
      this.getimgs();
      this.getinfo();
    },
    methods: {
      //动画3个方法
      beforeEnter(el) {
        //设定小球的初始位置
        el.style.transform = "translate(0px,0px)";
      },
      enter(el, done) {
        //保证小球出现动画
        el.offsetWidth;

        //设置小球的结束位置
        el.style.transform = "translate(75px,366px)";

        //结束动画
        done();
      },
      afterEnter(el) {
        //重置小球的初始状态
        this.isshow = !this.isshow;
      },
      //加入购物车方法
      toshopcar() {
        //触发事件
        vm.$emit(COUNTSTR, this.inputNumberCount);
        //2.0 将数据保存到localStroage中
        valueObj.goodsid = this.id;
        valueObj.count = this.inputNumberCount;
        setItem(valueObj);
        //3.0 实现小球动画
        this.isshow = !this.isshow;
      },

      //获取inputnumber组件中传入的值
      getcount(count) {
        this.inputNumberCount = count;
        console.log(count);
      },
      getimgs() {
        var url = '../../json/goodslunbo'   this.id   '.json';
        this.$http.get(url).then(function(res) {
          //判断状态
          this.imgs = res.body.message;
        });
      },
      getinfo() {
        var url = '../../json/goodslist.json';
        this.$http.get(url).then(function(res) {
          var body = res.body;
          if(body.status != 0) {
            alert(body.message);
            return;
          }

          for(var i = 0; i < body.message.length; i  ) {
            if(this.id == body.message[i].id) {
              console.log(body.message[i])
              this.info = body.message[i];
              console.log(this.info);
            }
          }
        });
      }

    }
  }
</script>

<style scoped>
  .silder {
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
    margin: 5px;
  }

  #buy,
  #params,
  #other {
    margin: 5px;
    padding: 5px;
    border: 1px solid rgba(0, 0, 0, 0.4);
    border-radius: 5px;
  }

  .line {
    height: 1px;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }

  #buy ul,
  #params ul {
    padding-left: 0px;
  }

  #buy h4 {
    color: #0094ff;
    padding: 5px;
  }

  #buy li,
  #params li {
    list-style: none;
    padding: 8px;
  }

  #buy .price span {
    color: red;
  }

  #other .imgdesc {
    margin-bottom: 20px;
  }

  .inputli {
    position: relative;
  }

  .inputnumber {
    position: absolute;
    left: 100px;
    top: 5px;
  }

  .ball {
    background-color: red;
    height: 20px;
    width: 20px;
    border-radius: 50%;
    position: absolute;
    left: 150px;
    top: 10px;
    transition: all 0.4s ease;
    z-index: 100;
  }
</style>

View Code

 

版权声明:本文由韦德娱乐1946_韦德娱乐1946网页版|韦德国际1946官网发布于网络编程,转载请注明出处:依照Vue的WebApp项目支出,文件操作