[Vue]6. 动态路由 模拟新增文章功能

Demo:https://gitee.com/animalcoder/Vue/tree/master/vue6

版本:Vue-cli:4.2.9

效果:

可以新建文章   ↓

然后每个文章对应不同的动态url,对应不同title  content

 

 

添加动态路由思路:

1.Vuex维护List,List里是每个文章的  title , id, content

   Vuex维护一个id,表示当前文章id是多少,

   添加文章页面,每提交一篇文章,id+=1

2.新建一个组件X,当作文章的模板,根据url上不同的id 显示不同的title content

3.路由设置里url绑定id,组件为X

4.主页面列表List添加点击跳转事件

 

1.  store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

let defaultlist=[{title1:"test",content1:"test",id:"1"}]
try {//
    if(localStorage.getItem("list1")){
        defaultlist=JSON.parse(localStorage.getItem("list1"))
    }
}catch(e){
}


let defaultid=2;
try {//
    if(localStorage.getItem("id1")){
        defaultid=JSON.parse(localStorage.getItem("id1"))
    }
}catch(e){
}

export default new Vuex.Store({
    state:{//状态
        lists:defaultlist
        ,  id:defaultid  
    },
    mutations: {  //更改事件

        addItems (state , value){
            state.lists.push(value)
            localStorage.setItem("list1",JSON.stringify(state.lists))
        },


    },
    actions: {

    },
    getters: {
        getTodoById: (state) => (id) => {
            return state.lists.find(todo => (todo.id == id))
        },
        getTodoById2:function(state,actions){  // == ===
            let x=function(id) {
                return  state.lists.find(todo => todo.id === id)
            }
            console.log("x"+x)
            return x;
        },
        // getTodoById2(id) { 
        //     return  this.state.lists.find(todo => todo.title1 === id)
        // }
    }


})

添加文章Son2.Vue页面:

<template>
    <div style="text-align:left">
        <h2>son2</h2>
        <p>标题</p>
        <input type='text' v-model="title"/>
        <p>内容</p>
        <textarea type='text' v-model='content' rows="5" cols="50"/>
        <br>
        <el-button  @click="add()">提交</el-button>
        <p v-if="sum>3">{{sum}}>3</p>
        <p v-else>{{sum}}<=3</p>
    </div>
</template>


<style scoped>
    
</style>


<script>
import store from '@/store' //引入store存储 (vuex)
export default {
    store,
    //data(){}里要 return{}
    data(){
      return {   
        title: '',
        content: '',
        sum:1,
      }
    },
    methods:{
        add(){
            let x=localStorage.getItem("id1") 
            x++;
            localStorage.setItem("id1",x);
            store.commit('addItems',{ title1: this.title,content1: this.content,id:x}) //调用store的方法 value传参
            
            this.title='';
            this.content='';
            this.$router.push('/Hellocopy/Son1'); 
        }
    }

}
</script>

2. 文章组件Test.Vue  核心是  let x = this.$route.params.id;获取url上的id

<template>
  <div>
    <h1>{{title}}</h1>
    <div >
      <el-row type="flex" justify="center">
        <el-col :span="15" >
          <el-card class="box-card" >
            <div style="min-height:500px">
                <p style="text-align:left">content:{{content}}</p>

            </div>
            
          </el-card>
        </el-col>
      </el-row>
    </div>

    <p>id:{{id}}</p>
    <!-- <button @click="getFuck()">123</button> -->
  </div>
</template>
<style scoped>

</style>

<script>
import store from "@/store"; //取出存储器里面的lists
export default {
  store,
  data() {
    return {
      title: "",
      content: "",
      id: ""
    };
  },
  methods: {
    getFuck() {}
  },
  mounted() {
    let x = this.$route.params.id;
    let ans = store.getters.getTodoById(x);
    console.log("ans" + ans);
    this.title = ans.title1;
    this.content = ans.content1;
    this.id = ans.id;
  }
};
</script>

 

3. main.js  核心是这句:{ path: '/user/:id',name:'/user/:id', component: Test }

import Vue from 'vue'
import App from './App.vue'
import HelloWorld from '@/components/HelloWorld'
import Hecopy from '@/components/Hecopy'
import ElementUI from "element-ui"
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
import Test from '@/components/Test'

import  Son1 from '@/components/Son1'
import  Son2 from '@/components/Son2'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
 
const routes = [
    {path: '/',component: HelloWorld},
    {
      path: '/Hellocopy',
      name: 'Hellocopy',
      component: Hecopy,
      children: [
        {
          path: 'Son1',
          name: 'Son1',
          component:Son1 
        },
        {
          path: 'Son2',
          name: 'Son2',
          component:Son2
        }
        ,{ path: '/user/:id',name:'/user/:id', component: Test }//绑定url 与 id
      ]
    },
    {
        path: '/Test',
        name: 'Test',
        component:Test
    } 
    

]
const router = new VueRouter ({
  routes,
  //mode: 'history' //发布时把这个删掉
})
const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  render: h => h(App),
  data(){
    return{
        aa:123456
    }
},
}).$mount('#app')

4.主页面Son1.Vue  核心函数是Jump()

 Jump(id){
        this.$router.push('/user/'+id); 
 }
<template>
  <div class="test">
    <h2>son1</h2>
    <el-row :gutter="36" >
      <el-col :span="12">
        <el-card shadow="hover">
          <a :href="url">111</a>
          <p :title="url"></p>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <div @click="Add(2,3)">123+{{Add(2,3)}}</div>

          <div>123+{{TestFunction("32")}}</div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="36" type="flex" justify="center">
      <ul>
        
        <li v-for="(item,idx) in pageLists" :key="idx" style="color:black;">
          <!-- for 绑定 lists + 绑定下标 -->
          <!-- {{item.title1}}-{{item.content1}} -->
          
          <el-col :span="12" >
            <el-card shadow="hover" >
              <div style="height:200px">
                
                <el-image
      style="width: 100%; height: 200px;min-width:200px;opacity:0.9;"
      :src="url"
      :fit="fit"></el-image>
                
              </div>
              <div @click="Jump(item.id)"  class="bottom clearfix"> <p  class="title">{{item.title1}}</p></div>
             
            </el-card>
          </el-col>
        </li>
      </ul>
    </el-row>
  </div>
</template>

<style scoped>
body {
  color: black;
}
ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
li {
  display: inline;
}
.el-col {
  margin-bottom: 20px;
}
.test {
  display: flex;
  flex-direction: column;
}
.title{
   font-size: 30px;
   text-align:left 
}
</style>


<script>
import store from "@/store"; //取出存储器里面的lists
export default {
  name: "List",
  store,
  computed: {
    //动态监听变化
    pageLists: () => store.state.lists
  },
  data() {
    return {

      a: 2,
      b: 3,
      sum: 0,
      url: "/img/12.jpg",
      fit:"cover",
      lists1: [
        { name: "123", age: "32" },
        { name: "1123", age: "323" }
      ]
    };
  },
  methods: {
    Add: (a, b) => {
      //console.log("???"+store.getters.getTodoById("123456"));
      return a + b;
    },
    TestFunction: function(id) {
      //不会报错 等价于 Add2()
      // console.log("store" + store + "com" + this.$options);
      let x = todo => todo.age === id;
      console.log(this.lists1.find(x));
      return this.lists1.find(function(todo) {
        return todo.age === id;
      });
    },
    Jump(id){
        this.$router.push('/user/'+id); 
    }
  },
  mounted() {
    console.log(this.$options);
    //localStorage.clear();
  }
};
</script>

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值