I develop a ecommerce website with Vue.js2,
for the single product page, I have a route like
{
path: '/product/:code',
name: 'product',
props:true,
component: Product
},
And in the component I have somthing like
props: {
code: {
type:String
}
},
data: ()=> {
return {
product:{}
}
},
beforeMount(){
axios
.get('http://127.0.0.1:8000/api/products/'+this.code)
.then((response) => {
this.plan = response.data,
this.ListImages = response.data.ListImages;
console.log(this.ListImages)
console.log(this.plan)
})
}
The data is retrieved but the component is already create but if I do the request "beforeCreate()" the "this.code" is "undefined" and when I use "$router.params.code" an error is occured stating that "$router" is not the define.
Please can I have some help?
You should be able to use it like this:
this.$route.params.code
In the component, You can use this:
User {{ $route.params.getUserName }}
Route.js
{
path: "/#:getUserName",
name: "profile",
component: () => import("../views/ProfileView.vue"),
}
Related
I have a List component where I fetch my date from db/blogs.json:
created() {
fetch('http://localhost:3000/blogs')
.then(response => {
return response.json();
})
.then(data => {
this.blogs = data;
})
},
In my BlogDetail.vue I have:
<script>
export default {
data: () => {
return {
blogId:this.$route.params.id
}
},
computed: {
blog() {
return this.blogs.find(
blog => blog.id === this.blogId
)
}
}
}
</script>
But how do I get the blogs data in this component, which I fetched in the List component?
Because now in the <template> section of my BlogDetail.vue I cannot access e.g. {{ blog.name }}
Update:
I try passing blogs with props:
Now I am accepting a prop in BlogDetails.vue:
props: {
blogs: {
type: Array
}
},
But from where (which component), I have to registering the prop like :blogs="blogs"?
Update 2:
This is what I have so far, link to the sandbox
Here is the working sandbox.
Firstly you need to import JSON data from your JSON file correctly. As:
<script>
import ListItem from "./ListItem";
import Blogs from "../../public/db/blogs.json";
export default {
name: "List",
components: {
ListItem
},
data() {
return {
blogs: Blogs.experiences
};
},
created() {}
};
</script>
Have to send props in the router-link as :
<router-link
:to="{ name: 'BlogDetails', params: { id: blog.id,blog:blog }}">More information
</router-link>
You can send props to the child component in the tag name, in your case:
//LIST component(PARENT)
<tamplate>
<BlogDetail :blogs="blogs"></BlogDetail> //CHILD component
</template>
I'm running VueJS with vue router installed, the titles are currently working OK except from one detail.
In the example below all pages work OK, however if I use the /user/:user_id route to display a specific user I don't know how to show the username in the title, e.g: 'Cool Page - [USER_NAME]'.
This username is obtained in the Component from the database after the component uses the :user_id to retrieve that users data from Vuex.
How can I do this?
routes: [
{
path: '/',
name: 'Home',
component: Home,
meta: {'title': "Cool Page",
'metaTags': metaTags},
},
{
path: '/users',
name: 'users',
component: Users,
meta: {'title': "CoolPage - Users",
metaTags: metaTags},
},
{
path: '/user/:user_id',
name: 'user',
component: User,
meta: {'title': "Cool Page - Some User",
metaTags: metaTags },
...
const DEFAULT_TITLE = 'Coolpage.com';
router.afterEach((to, from) => {
document.title = to.meta.title || DEFAULT_TITLE;
});
In my Component:
I have a computed property to use the vuex getter, and a data variable for the prop, like this:
computed: {
...mapGetters(['allUsers','getUserById', 'getUserStoreStatus']),
user: function () {
var u = this.getUserById(this.user_id);
if(u){ return u; }
else{ return {}; }
},
},
data(){
return {
user_id: this.$route.params.user_id,
}
}
...
I would simply import your store where you are getting the user info, like this:
import store from '../store';
Then you will do something like this (I haven't seen your store code so you'll have to alter this bit to fit your needs):
const DEFAULT_TITLE = 'Coolpage.com';
router.afterEach((to, from) => {
const userInfo = store.getters['getUserInfo'];
// This could be cleaned up a bit, but you get the point...
document.title = to.name === 'user' ?
`Cool Page - ${userInfo.username}` :
to.meta.title || DEFAULT_TITLE;
});
I am trying to pass data through router. My code is working but it shows data in url. I don't want that like as POST method.url should like /data-list . Also I want to catch passing value from component. Here I did not use vuex . Actually my job is to show message that task is done based on this data. I am using Laravel for backend. Thanks in advance
1st component
axios.post("/request/data", dataform).then(function (resp) {
app.$router.push({ path: "/data-list/" + resp.data.success });
});
routes
{
path: '/data-list/:message?',
name: 'dataList',
component: dataList,
meta: {
auth: true
}
},
Another component. Here I want to catch
mounted() {
var app = this;
app.message = app.$route.params.message;
}
So if I understand correctly, you are fetching data in some component and then you are doing a router-push to dataList component.
You want to access the data in dataList component.
Since you always want the route to be /dataList, do this in your routes file
{
path: '/data-list', //removing dynamic tag.
name: 'dataList',
component: dataList,
meta: {
auth: true
}
},
Then in the component where you do router push, add a handleClick like so.
handleClick() {
let data = {
id: 25,
description: "pass data through params"
};
this.$router.push({
name: "dataList", //use name for router push
params: { data }
});
}
}
Then in your dataList component you can access the data passed in the mounted like so :
mounted() {
let data = this.$route.params.data;
console.log("data is", data);
}
Working implementation attached below.
You can push router data in router like this.
this.$router.push({
name: "dataList",
params: { data: resp.data },
});
and in the routes you can define your route as
{
path: "/dataList",
name: "dataList",
props: true,
meta: { title: "Data list" },
component: () => import("path to datalist component")
},
and in the DataList.vue you can use props to get the data
export default {
props:['data'],
mounted(){
alert(this.data);
}
}
I have my index book that list all the registered books and when I click to edit a specif book it does get the specif book's id in the route but my props element does not get it, what gives an error!
How can I fix it?
Below I have the code on my index page:
<router-link :to="{ name: 'update_book', params: {id: book.id} }">
<font-awesome-icon icon="pen-square" />
</router-link>
In my update page I have:
<script>
props: ['id'],
data() {
return {
books: [],
};
},
methods: {
getBook(id) {
axios.get(`http://localhost:3000/api/v1/books/${id}`) // Gets an specif book
.then((response) => { this.books = response.data; });
},
created() {
this.getBook(this.id);
},
watch: {
$route() {
this.getBook(this.id);
},
Router do not pass id to props.In your case you can find id in this.$route.params
Even if you use something like /book/:id in router itself, that id param will live in this.$route.params.id.
So you need something like :
created() {
this.getBook(this.$router.params.id);
},
And btw, in watcher too.
I have a route created with vue-router.
{
path: '/events/:id',
component: Event,
name: 'Event',
meta: {
title: 'Design Web'
}
},
In "meta", I give it the name of my page.
I can call the title of my page by doing this: $route.meta.title
But now, I'm facing a problem. In the title of my page, I would like to pass a variable (the name of my event).
meta: {
title: $nameOfEvent
}
How to do ?
Thank you
It is possible if you define the title attribute as a function :
{
meta: { title: route => { /* return custom title based on route, store or anything */ } }
}
and
router.beforeEach((to, from, next) => {
if (to.meta.title) {
document.title = to.meta.title(to);
}
next();
})
Codepen: https://codepen.io/anon/pen/roRmdo?editors=1111 (you need to inspect inner iframe to see the title change).
or create a directive:
Vue.directive('title', {
inserted: (el, binding) => document.title = binding.value,
update: (el, binding) => document.title = binding.value
})
Then use that directive on the router-view component:
<router-view v-title="title" ></router-view>
Component:
export default {
data(){
return {
title: 'This will be the title'
}
}
}
Source: https://github.com/vuejs/vue-router/issues/914