Vue学习:六

Vue学习

  • 一、生产环境
  • 二、Vue3-reactive
  • 三、Vue3-通信和生命周期
    • <1>.ref
    • <2>.todo-ref
    • <3>.toRef
    • <4>.props
    • <5>.lifecycle
    • <6>.computed
    • <7>.watch
    • <8>.app
  • 四、Vue3-router和store
    • <1>.router
    • <2>.store

一、生产环境

<template>
  <div>
    <van-nav-bar title="影院" ref="navbar" @click-left="handleLeft" @click-right="handleRight">
      <template #left>
        {{ cityName }}<van-icon name="arrow-down" />
      template>
      <template #right>
        <van-icon name="search" size="28" color="black" />
      template>
    van-nav-bar>

    <div class="box" :style="{
      height: height,
    }">
      <ul>
        <li v-for="data in cinemaList" :key="data.cinemaId">
          <div class="left">
            <div class="cinema_name">{{ data.name }}div>
            <div class="cinema_text">{{ data.address }}div>
          div>

          <div class="right cinema_name">
            <div style="color: red">¥{{ data.lowPrice / 100 }}起div>
          div>
        li>
      ul>
    div>
  div>
template>
<script>
import BetterScroll from 'better-scroll'
import { mapState, mapActions, mapMutations } from 'vuex' // export {mapState}
// console.log(mapState(['cinemaList']))
export default {
  data() {
    return {
      height: '0px'
    }
  },
  computed: {
    a() {
      return '1111'
    },
    ...mapState(['cinemaList', 'cityId', 'cityName'])
  },

  mounted() {
    // console.log(this.$refs.navbar.$el.offsetHeight)
    // 动态结算高度
    this.height =
      document.documentElement.clientHeight -
      this.$refs.navbar.$el.offsetHeight -
      document.querySelector('footer').offsetHeight +
      'px'

    // 分发

    if (this.cinemaList.length === 0) {
      this.getCinemaData(this.cityId).then(res => {
        this.$nextTick(() => {
          new BetterScroll('.box', {
            scrollbar: {
              fade: true
            }
          })
        })
      })
    } else {
      console.log('缓存')
      this.$nextTick(() => {
        new BetterScroll('.box', {
          scrollbar: {
            fade: true
          }
        })
      })
    }

    // http({
    //   url: `/gateway?cityId=${this.$store.state.cityId}&ticketFlag=1&k=5121167`,
    //   headers: {
    //     'X-Host': 'mall.film-ticket.cinema.list'
    //   }
    // }).then((res) => {
    //   //   console.log(res.data.data.cinemas)
    //   this.cinemaList = res.data.data.cinemas
    //   //   console.log(document.getElementsByTagName('li').length)

    //   this.$nextTick(() => {
    //     new BetterScroll('.box', {
    //       scrollbar: {
    //         fade: true
    //       }
    //     })
    //   })
    // })
  },
  methods: {
    ...mapActions(['getCinemaData']),
    ...mapMutations(['clearCinema']),
    handleLeft() {
      // console.log('left')
      this.$router.push('/city')

      // 清空cinemaList
      this.clearCinema()
    },
    handleRight() {
      this.$router.push('/cinemas/search')
    }
  }
}
script>
<style lang="scss" scoped>
li {
  padding: 0.833333rem;

  display: flex;
  justify-content: space-between;

  .left {
    width: 11.777778rem;
  }

  .cinema_name {
    font-size: 15px;
  }

  .cinema_text {
    color: #797d82;
    font-size: 12px;
    margin-top: 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.box {
  // height: 34.333333rem;
  overflow: hidden;
  position: relative;
  // 修正滚动条的位置
}
style>

<template>
  <div class="city">
    <van-index-bar :index-list="computedList" @select="handleChange">
      <div v-for="data in cityList" :key="data.type">
        <van-index-anchor :index="data.type" />

        <van-cell :title="item.name" v-for="item in data.list" :key="item.cityId" @click="handleClick(item)" />
      div>
    van-index-bar>
  div>
template>
<script>
import http from '@/util/http'
import { Toast } from 'vant'
import obj from '@/util/mixinObj'
export default {
  mixins: [obj], // 混入
  data() {
    return {
      cityList: []
    }
  },
  computed: {
    computedList() {
      return this.cityList.map(item => item.type)
    }
  },

  mounted() {
    //
    http({
      url: '/gateway?k=5066709',
      headers: {
        'X-Host': 'mall.film-ticket.city.list'
      }
    }).then((res) => {
      //   console.log(res.data.data.cities)
      this.cityList = this.renderCity(res.data.data.cities)
      // 1, 316条 ==> A ,B进行分组
      // 2.  利用转换后的数组,结合组件库进行渲染页面。
    })
  },
  methods: {
    handleChange(data) {
      //   console.log('change', data)
      Toast(data)
    },
    renderCity(list) {
      console.log(list)
      var cityList = []
      var letterList = []
      for (var i = 65; i < 91; i++) {
        // console.log(String.fromCharCode(i))
        letterList.push(String.fromCharCode(i))
      }

      //   console.log(letterList)
      letterList.forEach((letter) => {
        var newList = list.filter(
          (item) => item.pinyin.substring(0, 1).toUpperCase() === letter
        )
        // console.log(newList)

        newList.length > 0 &&
          cityList.push({
            type: letter,
            list: newList
          })
      })

      //   console.log(cityList)
      return cityList
    },
    handleClick(item) {
      //   console.log(item.name, item.cityId)

      // 传统的多页面方案
      //  1. location.href = '#/cinemas?cityname=' + item.name
      //  2. cookie , localStorage

      // 单页面方案,
      //  1. 中间人模式
      //  2. bus事件总线 $on ,$emit

      // vuex- 状态管理模式

      //   console.log()
      //   this.$store.state.cityName = item.name //

      this.$store.commit('changeCityName', item.name)
      this.$store.commit('changeCityId', item.cityId)
      this.$router.back()
    }
  }
}
script>
<style lang="scss" >
.van-toast--html,
.van-toast--text {
  min-width: 30px;
}
style>

二、Vue3-reactive

<template>
  <div>
    <van-button type="primary" :round="true">主要按钮van-button>
    <van-button type="info">信息按钮van-button>
    <van-button type="default">默认按钮van-button>
    <van-button type="warning">警告按钮van-button>
    <van-button type="danger">危险按钮van-button>

    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item>1van-swipe-item>
      <van-swipe-item>2van-swipe-item>
      <van-swipe-item>3van-swipe-item>
      <van-swipe-item>4van-swipe-item>
    van-swipe>
  div>
template>

<style>
  .my-swipe .van-swipe-item {
    color: #fff;
    font-size: 20px;
    line-height: 150px;
    text-align: center;
    background-color: #39a9ed;
  }
style>

<template>
    <div>
        detail
    div>
template>

<script>
export default {
    mounted(){
        this.$store.commit("hide")
        console.log(this.$route.params.id)

    },
    beforeUnmount(){
        console.log("beforeUnmount")
    },
    unmounted(){
        this.$store.commit("show")
    }
}
script>
<template>
  <div>
    <ul v-show="$store.state.isTabbarShow">
      <router-link to="/films" custom v-slot="{ navigate, isActive }">
        <li @click="navigate" :class="isActive ? 'zzyactive' : ''">
          <i class="iconfont icon-all">i>
          <span>电影span>
        li>
      router-link>
        <router-link to="/cinemas" custom v-slot="{ navigate, isActive }">
        <li @click="navigate" :class="isActive ? 'zzyactive' : ''">
          <i class="iconfont icon-all">i>
          <span>影院span>
        li>
      router-link>
        <router-link to="/center" custom v-slot="{ navigate, isActive }">
        <li @click="navigate" :class="isActive ? 'zzyactive' : ''">
          <i class="iconfont icon-all">i>
          <span>我的span>
        li>
      router-link>
    ul>
    <router-view>router-view>
  div>
template>
<script>
export default {
  data(){
    return {
      mytext:''
    }
  },
  components:{
    
  },
  //局部指令
  directives:{
    hello:{
      mounted(){
        console.log("moutend")
      }
    }
  }
}
script>

<style lang="scss" scoped> 
.zzyactive{
  color:red;
}
style>
import { createApp } from 'vue'
import App from './base/02-todo.vue'
import router from './router'
import store from './store'

import Vant from 'vant';
import 'vant/lib/index.css';

createApp(App)
    .use(router)
    .use(store)
    .use(Vant)
    .mount('#app')
//Vue.createApp
<template>
    <div>
        hello3- 新写法
        {{obj.myname}}
        <button @click="handleClick()">chnagebutton>

        
    div>
template>

<script>
import {reactive} from 'vue'
export default {
    // vue3老写法或者vue 写法 中 beforeCreeate,created 生命周期=== setup
    setup(){
        console.log("setup")

        //定义状态
        const obj = reactive({
            myname:"zzy",
            myage:100
        })
        const handleClick=()=>{
            // console.log("111111111")
            obj.myname = 'xiaoming'
        }
        return {
            obj,
            handleClick
        }
    }
}
script>

<template>
    <div>
        todo--{{ myname }}
        <input type="text" v-model="obj.mytext" />
        <button @click='handleAdd'>addbutton>

        <ul>
            <li v-for='data in obj2.datalist' :key="data">
                {{ data }}
            li>
        ul>

        <ul>
            <li v-for='data in mylist' :key="data">
                {{ data }}
            li>
        ul>
    div>
template>

<script>
import { reactive } from 'vue'
export default {
    data() {
        return {
            myname: "zzy"
        }
    },
    mounted() {
        // console.log("breforeCreate",obj)
    },

    setup() {
        // console.log(this)
        const obj = reactive({
            mytext: '',
        })
        const obj2 = reactive({
            datalist: []
        })

        const mylist = reactive([])

        const handleAdd = () => {
            // console.log(obj.mytext)
            obj2.datalist.push(obj.mytext)
            mylist.push(obj.mytext)

            obj.mytext = ''
        }
        return {
            obj,
            obj2,
            mylist,
            handleAdd
        }
    }
}
script>

三、Vue3-通信和生命周期

<template>
    <div>
        detail
    div>
template>

<script>
export default {
    mounted(){
        this.$store.commit("hide")
        console.log(this.$route.params.id)

    },
    beforeUnmount(){
        console.log("beforeUnmount")
    },
    unmounted(){
        this.$store.commit("show")
    }
}
script>
在这里插入代码片

<1>.ref

<template>
    <div>
        hello3- ref-新写法
        {{ myname }}
        <button @click="handleClick()">chnagebutton>


    div>
template>

<script>
import { ref } from 'vue'
export default {
    // vue3老写法或者vue 写法 中 beforeCreeate,created 生命周期=== setup
    setup() {
        const myname = ref("zzy") // .value 属性
        // console.log(myname)
        const handleClick = () => {
            myname.value = "xiaoming"
        }

        return {
            handleClick,
            myname
        }

    }
}
script>

<2>.todo-ref

<template>
    <div>
        <input type="text" ref="mytext">

        <button @click="handleAdd">addbutton>

        <ul>
            <li v-for="data in datalist" :key="data">
                {{data}}
            li>
        ul>
    div>
template>

<script>
import {ref} from 'vue'
export default {
    setup(){
        const mytext= ref()
        const datalist = ref(["111","222"])
        const handleAdd = ()=>{
            console.log(mytext.value.value)

            datalist.value.push(mytext.value.value)
        }
        return {
            mytext,
            handleAdd,
            datalist
        }
    }
}
script>

<3>.toRef

<template>
    <div>
        hello3- 新写法
        {{myname}}-{{myage}}
        <button @click="handleClick()">chnagebutton>

        
    div>
template>

<script>
import {reactive,toRefs} from 'vue'
export default {
    // vue3老写法或者vue 写法 中 beforeCreeate,created 生命周期=== setup
    setup(){
        console.log("setup")

        //定义状态
        const obj = reactive({
            myname:"zzy",
            myage:100
        })
        // console.log()
        const handleClick=()=>{
            // console.log("111111111")
            obj.myname = 'xiaoming'
        }
        return { 
            ...toRefs(obj),
            handleClick
        }
    }
}
script>

<4>.props

<template>
    <div>
        通信
        <navbar myname="home" myid="111" @event= "change">navbar>
        <sidebar v-show="obj.isShow">sidebar>
    div>
template>
<script>
import navbar from './components/navbar'
import sidebar from './components/sidebar'
import {reactive} from 'vue'
export default {
    components:{
        navbar,
        sidebar
    },
    setup(){
        const obj = reactive({
            isShow:true
        })

        const change = ()=>{
            obj.isShow = !obj.isShow
        }
        return {
            obj,
            change
        }
    }
}
script>

<5>.lifecycle

<template>
    <div>
        生命周期

        <ul>
            <li v-for="data in obj.list" :key="data">
                {{data}}
            li>
        ul>
    div>
template>

<script>
import axios from 'axios'
import { onBeforeMount, onMounted, reactive } from 'vue'
export default {
    data(){
        return {

        }
    },
    // mounted
    computed:{

    },
    setup(){
        const obj = reactive({
            list:[]
        })
        onBeforeMount(()=>{
            console.log("onBeforeMount")
        })

        onMounted(()=>{
            console.log("dom上树",`axios,事件监听, setInterval,,,,,,`)
            setTimeout(()=>{
                obj.list = ["aaa","vvvv","cccc"]
            },2000)
        })

        return {
            obj
        }
    }
}
script>

<6>.computed

<template>
    <div>
        <input type="text" v-model="obj.mytext" />
        <ul>
            <li v-for="data in computedList" :key="data">
                {{ data }}
            li>
        ul>

        {{ filterlist() }}
        {{ filterlist() }}

        {{ computedList }}
        {{ computedList }}
    div>
template>
<script>
import { reactive, computed } from 'vue'
export default {
    setup() {
        const obj = reactive({
            mytext: '',
            datalist: ["aaa", "abb", "abc", "bbb", "bcc", "add", "bcd"]
        })
        const filterlist = () => {
            console.log("filterlist")
            return obj.datalist.filter(item => item.includes(obj.mytext))
        }

        const computedList = computed(() => {
            console.log("computedList")
            return obj.datalist.filter(item => item.includes(obj.mytext))
        })
        return {
            obj,
            filterlist,
            computedList
        }
    },
    computed: {
        aaa() {
            return "111111"
        }
    }
}
script>

<7>.watch

<template>
  <div>
    <input type="text" v-model="obj.mytext" />
    <ul>
      <li v-for="data in obj.datalist" :key="data">
        {{ data }}
      li>
    ul>
  div>
template>
<script>
import { reactive, watch } from "vue";
export default {
  setup() {
    const obj = reactive({
      mytext: "",
      datalist: ["aaa", "abb", "abc", "bbb", "bcc", "add", "bcd"],
      oldlist: ["aaa", "abb", "abc", "bbb", "bcc", "add", "bcd"],
    });

    watch(
      () => obj.mytext,
      () => {
        obj.datalist = obj.oldlist.filter((item) => item.includes(obj.mytext));
      }
    );

    const handleInput = () => {};
    return {
      obj,
      handleInput,
    };
  },
  watch:{
      mytext(){
          
      }
  }
};
script>

<8>.app

<template>
    <div>
        app

        <ul>
            <li v-for="data in obj1.list" :key="data.name">
                {{ data.name }}
            li>
        ul>

        <ul>
            <li v-for="data in obj2.list" :key="data.title">
                {{ data.title }}
            li>
        ul>
    div>
template>

<script>
// import axios from 'axios'
// import { onMounted, reactive } from 'vue'
import { getData1, getData2 } from './module/app'
export default {
    setup() {
        const obj1 = getData1()
        const obj2 = getData2()

        return {
            obj1,
            obj2
        }
    }
}
script>

四、Vue3-router和store

<template>
    <div>
        detail
    div>
template>

<script>
import { inject, onMounted, onUnmounted } from 'vue'
import {useRoute} from 'vue-router'
import {useStore} from 'vuex'
export default {
    // mounted(){
    //     this.$store.commit("hide")
    //     console.log(this.$route.params.id)

    // },
    // beforeUnmount(){
    //     console.log("beforeUnmount")
    // },
    // unmounted(){
    //     this.$store.commit("show")
    // }

    setup(){
        const route = useRoute()  // route === this.$route
        const store = useStore() // store === this.$store
        
        const isShow = inject("zzyshow")
        onMounted(()=>{
            store.commit("hide")
            console.log(route.params.id)    
            
            isShow.value = false
        })

        onUnmounted(()=>{
            store.commit("show")

            isShow.value = true
        })
    }
}
script>

<1>.router

import { createRouter, createWebHashHistory } from 'vue-router'
import Film from '../views/Film.vue'
import Nowplaying from '../views/films/Nowplaying.vue'
import Comingsoon from '../views/films/Comingsoon.vue'
import Cinema from '../views/Cinema.vue'
import Detail from '../views/Detail.vue'
import Center from '../views/Center.vue'
const routes = [
  {
    path: '/films',
    component: Film,
    name: 'film',
    children: [
      {
        path: '/films/nowplaying',
        component: Nowplaying
      },
      {
        path: '/films/comingsoon',
        component: Comingsoon
      },
      {
        path: '/films',
        redirect: '/films/nowplaying'
      }
    ]
  },
  {
    path: '/cinemas',
    component: Cinema
  },
  {
    path: '/detail/:id',
    component: Detail
  },
  {
    path: '/center',
    component: Center
  },
  {
    path: '/',
    redirect: '/films'
  },
  {
    path: '/:anywadadaddada',
    redirect: {
      name: 'film'
    }
  }
]

const router = createRouter({
  // history: createWebHistory(),// history 模式
  history: createWebHashHistory(), //hash 模式
  routes
})
// router.beforeEach
export default router

<2>.store

import { createStore } from 'vuex'

export default createStore({
  state:{
    isTabbarShow:true
  },
  mutations:{
    hide(state){
      state.isTabbarShow = false
    },
    show(state){
      state.isTabbarShow = true
    }
  }
})

你可能感兴趣的:(vue.js,学习,javascript)