Successively bind list item values, from list to page, in a layout rendered within another layout - list

The best example to illustrate what I am trying to develop is a desktop email application.
On the left there is a vertical menu (on a quasar q-drawer).
Next, also on the left, there is a mailing list (on a quasar q-list within a q-drawer).
When each item is selected, the corresponding content is displayed on the right (on a quasar q-page).
Expected operation:
The list is loaded once and when I successively select the various items in the list, only the content on the right should be used and the content updated according to the id sent as a parameter in the request.
Note that the list component is only rendered once; that is, it is not rendered again each time a item is selected from the list and remains visible while the content is displayed on the right
The problem:
When I select the first item in the mailing list it works correctly and as expected, the mail content is displayed on the q-page.
When I select a second item from the list it doesn't work anymore and the following error is displayed on the console:
Uncaught (in promise) NavigationDuplicated {_name:
"NavigationDuplicated", name: "NavigationDuplicated", message:
"Navigating to current location ("/mailcontent") is not allowed",
stack: "Error at new NavigationDuplicated
(webpack-int…node_modules/vue/dist/vue.runtime.esm.js:1853:26)"}
I would appreciate suggestions on how to resolve this issue.
The following code is intended to illustrate the problem in the main part:
Routes: secondlayout is the child of another layout
const routes = [
{
path: "/index",
component: () => import("layouts/AppLayout.vue"),
children: [
{ path: "/home", component: () => import("pages/Home.vue") },
{
path: "secondlayout",
component: () => import("Layouts/MailsPlace.vue"),
children: [
{ path: "/mailcontent", name: 'mailcontent', component: () => import("pages/MailContent.vue") },
]
}
]
}
];
Second layout where the email application (list and content) is rendered with q-drawer and router-view
<template>
<q-layout view="lhh LpR lff" container class=" myclass shadow-2 window-height" >
<q-drawer
style="full-height"
v-model="drawerLeft"
:width="500"
:breakpoint="700"
elevated
content-class="bg-grey-1"
>
<q-scroll-area
class="fit"
style="margin-top:80px">
<q-list separator padding>
<q-separator />
<list-mails
v-for="(mail, index) in mails"
:mail="mail"
:key="mail.id_mail"
:id="index">
</list-mails>
<q-separator />
</q-list>
</q-scroll-area>
</q-drawer>
<q-page-container>
<router-view></router-view>
</q-page-container>
</template>
<script>
export default {
data () {
return {
mails: {},
drawerRight: false,
}
},
/* watch: {
$route(to, from) {
console.log('after', this.$route.path);
}
},
beforeRouteUpdate(to, from, next) {
console.log('before', this.$route.path);
next();
},*/
components: {
'list-mails': require("pages/ListMails.vue").default,
},
created: function() {
this.listMails()
},
methods: {
listMails(){
this.$axios.get("/listmails")
.then(response => {
if (response.data.success) {
this.mails = response.data.mails.data;
} else {
showErrorNotify('msg');
}
})
.catch(error => {
showErrorMessage(error.message);
});
}
}
</script>
Mail list item with mailitemclick method
<template>
<q-item
clickable
v-ripple
exact
#click="mailitemclick(mail.id_mail)"
>
<q-item-section>
<q-item-label side lines="2"> {{ mail.title_mail }}</q-item-label>
</q-item-section>
</q-item>
</template>
<script>
export default {
props: ["mail"],
methods:{
mailitemclick(id){
this.$router.push({
name: 'mailcontent',
params: {id:id}
});
}
}
}
</script>
Mail content
<template>
<q-page class="fit row wrap justify-center tems-start content-start" style="overflow: hidden;">
<div style="padding:5px; margin:0px 0px 20px 0px; min-width: 650px; max-width: 700px;" >
<q-item>
<q-item-label class="titulo"> {{ mail.title_mail }} </q-item-label>
<div v-html="mail.content_mail"></div>
</q-item>
</div>
</q-page>
</template>
<script>
export default {
name: 'mailcontent',
data() {
return {
mail: {},
};
},
created() {
this.$axios.get(`/mailcontent/${this.$route.params.id}`)
.then(response => {
if (response.data.success) {
this.mail = response.data.mail[0])
} else {
showErrorNotify('msg');
}
})
.catch(error => {
showErrorMessage(error.message);
});
}
}
</script>

This happened to me when I had a router-link pointing to the same route. e.g. /products/1.
The user is able to click on the products, but if a product was
already clicked (and the component view was already loaded) and the
user attempts to click it again, the error/warning shows in the
console.
You can solve this by adding catch block.
methods: {
mailitemclick(id) {
this.$router.push({
name: 'mailcontent',
params: {'id': id}
}).catch(err => {});
}
},
But in the mail-content, you need to use watch for calling function and in mounted for first-time calling.
Temp Example -
data() {
return {
mail: {},
test_mails: {
12: {
content_mail: '<div>test 12<div>'
},
122:{
content_mail: '<div>test 122<div>'
}
}
}
},
mounted() {
this.mail = this.test_mails[this.$route.params.id]
},
watch:{
'$route':function () {
this.mail = this.test_mails[this.$route.params.id]
}
}
OR
You can use :to in list-mail to avoild click and catch -
<q-item
clickable
v-ripple
exact
:to="'/mailcontent/'+mail.id_mail"
>
<q-item-section>
<q-item-label side lines="2"> {{ mail.title_mail }}</q-item-label>
</q-item-section>
</q-item>
children: [
{ path: '', component: () => import('pages/Index.vue') },
{
path: "secondlayout",
component: () => import("layouts/mail-place.vue"),
children: [
{ path: "/mailcontent/:id", name: 'mailcontent', component: () => import("pages/mail-content.vue") },
]
}
]

Related

How to use PUT to update something in Vue using Django REST framework

I am new to Vue but have experience with Django. I am using this boilerplate from Github: https://github.com/gtalarico/django-vue-template
I really like the structure of that boilerplate because it is not overwelming at all and not a lot of code is written to succesfully interact with the back-end API of Django.
It has GET, POST & DELETE already pre-installed and connected to Django REST. So far so good. However I try to add a PUT method to it so I can update models. I try to follow the same structure but I can't get it to work.
My productService.js:
import api from '#/services/api'
export default {
fetchProducts() {
return api.get(`products/`)
.then(response => response.data)
},
postProduct(payload) {
return api.post(`products/`, payload)
.then(response => response.data)
},
deleteProduct(proId) {
return api.delete(`products/${proId}`)
.then(response => response.data)
},
updateProduct(proId) {
return api.put(`products/${proId}`)
.then(response => response.data)
}
}
The updateProduct is the new code I added.
Then in store --> products.js:
const actions = {
getProducts ({ commit }) {
productService.fetchProducts()
.then(products => {
commit('setProducts', products)
})
},
addProduct({ commit }, product) {
productService.postProduct(product)
.then(() => {
commit('addProduct', product)
})
},
deleteProduct( { commit }, proId) {
productService.deleteProduct(proId)
commit('deleteProduct', proId)
},
updateProduct( { commit }, proId) {
productService.updateProduct(proId)
commit('updateProduct', proId)
}
}
const mutations = {
setProducts (state, products) {
state.products = products
},
addProduct(state, product) {
state.products.push(product)
},
deleteProduct(state, proId) {
state.products = state.products.filter(obj => obj.pk !== proId)
},
updateProduct(state, proId) {
state.products = state.products.filter(obj => obj.pk !== proId)
}
}
Here again I added updateProduct.
Then in my Products.vue:
......
<b-tbody>
<b-tr v-for="(pro, index) in products" :key="index">
<b-td>{{ index }}</b-td>
<b-td variant="success">{{ pro.name }}</b-td>
<b-td>{{ pro.price }}</b-td>
<b-td>
<b-button variant="outline-primary" v-b-modal="'myModal' + index">Edit</b-button>
<b-modal v-bind:id="'myModal' + index" title="BootstrapVue">
<input type="text" :placeholder="pro.name" v-model="name">
<input type="number" :placeholder="pro.price" v-model="price">
<b-button type="submit" #click="updateProduct(pro.pk)" variant="outline-primary">Update</b-button>
</b-modal>
</b-td>
<b-td><b-button #click="deleteProduct(pro.pk)" variant="outline-primary">Delete</b-button></b-td>
</b-tr>
.....
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: "Products",
data() {
return {
name: "",
price: "",
};
},
computed: mapState({
products: state => state.products.products
}),
methods: mapActions('products', [
'addProduct',
'deleteProduct',
'updateProduct'
]),
created() {
this.$store.dispatch('products/getProducts')
}
};
</script>
Everything works fine except the PUT action to update a product. I figured that you have to use the ID of a product to be able to edit it with PUT. So that's why I used the same snippet as DELETE. But right now I am still deleting it instead of editing.
I also used now placeholder to display the text of a product entry, which is also not the correct way.. I want to use the modal to edit a product entry and then update it.
Can someone point me in the right direction?

Vue Warn: property "search" is not defined on instance

i'm creating a web app with a Django server with api from rest_framework and Vue as frontend (Nuxtjs in particular).
Trying to create a "search filter bar" i've got this error and i don't know why:
ERROR [Vue warn]: Property or method "search" is not defined on the instance but
referenced during render. Make sure that this property is reactive,
either in the data option, or for class-based components, by
initializing the property. See:
https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
This is my file.vue
<template>
<div>
<v-text-field v-model="search" label="search conditions" outlined dense></v-text-field>
</div>
<div>
<v-list v-for="condition in filteredConditions" :key="condition.id" >
<v-list-item>
<condition-card :onDelete="deleteCondition" :condition="condition"></condition-card>
</v-list-item>
</v-list>
</div>
</div>
</template>
<script>
import ConditionCard from "~/components/ConditionCard.vue";
export default {
head() {
return {
title: "Conditions list",
search: ""
};
},
components: {
ConditionCard
},
async asyncData({ $axios, params }) {
try {
let query = await $axios.$get(`/conditions/`);
if (query.count > 0){
return { conditions: query.results }
}
return { conditions: [] };
} catch (e) {
return { conditions: [] };
}
},
data() {
return {
conditions: []
};
},
...
...
computed: {
filteredConditions: function(){
return this.conditions.filter((condition) => {
return condition.name.toLowerCase().match(this.search.toLocaleLowerCase())
});
}
}
};
</script>
<style scoped>
</style>
The api is:
{"count":15,
"next":null,
"previous":null,
"results":[{"id":1,
"name":"Blinded",
"description":"A blinded creature can't see...",
"source_page_number":290},
{"id":2,
"name":"Charmed",
"description":"A charmed creature can't...",
...
...
Try to move the search variable from head() to data()
head() {
return {
title: "Conditions list"
}
},
...
data(){
return{
conditions: [],
search : ''
}
}

Jest, expected mock function to have been called, but it was not called

Testing lifecycle methods when a VueJS component renders on the transition group.
I've been writing tests for lifecycle methods when the component renders on the transition group of the following VueJS component I've made little progress on getting it to work and would appreciate advice regarding this. I also tried switching between shallow mounting and mounting the component though that seemed to make no difference.
import { shallowMount } from '#vue/test-utils';
import StaggeredTransition from '../src/index';
const staggeredTransitionWrapper = componentData =>
shallowMount(StaggeredTransition, {
...componentData,
});
const staggeredTransition = staggeredTransitionWrapper();
describe('StaggeredTransition.vue', () => {
it('should render a staggered transition component', () => {
expect(staggeredTransition.element.tagName).toBe('SPAN');
expect(staggeredTransition.html()).toMatchSnapshot();
});
it('should mock calling the enter method', () => {
const enterMock = jest.fn();
StaggeredTransition.methods.enter = enterMock;
const staggeredTransitionWrapper2 = componentData =>
shallowMount(StaggeredTransition, { ...componentData });
const staggeredTransition2 = staggeredTransitionWrapper2({
slots: {
default: '<h1 :key="1">Staggered transition test</h1>',
},
});
expect(enterMock).toBeCalled();
});
});
Code for the StaggeredTransition component
<template>
<transition-group
:tag="tag"
:name="'staggered-' + type"
:css="false"
appear
#before-enter="beforeEnter"
#enter="enter"
#leave="leave"
>
<slot />
</transition-group>
</template>
<script>
const { log } = console;
export default {
name: 'StaggeredTransition',
props: {
type: {
type: String,
options: ['fade', 'slide'],
required: false,
default: 'fade',
},
tag: {
type: String,
required: false,
default: 'div',
},
delay: {
type: Number,
required: false,
default: 100,
},
},
methods: {
beforeEnter(el) {
console.log('beforeEnter');
el.classList.add(`staggered-${this.type}-item`);
},
enter(el, done) {
console.log('enter');
setTimeout(() => {
el.classList.add(`staggered-${this.type}-item--visible`);
done();
}, this.getCalculatedDelay(el));
},
leave(el, done) {
console.log('leave');
setTimeout(() => {
el.classList.remove(`staggered-${this.type}-item--visible`);
done();
}, this.getCalculatedDelay(el));
},
getCalculatedDelay(el) {
console.log('getCalculatedDelay');
if (typeof el.dataset.index === 'undefined') {
log(
'data-index attribute is not set. Please set it in order to
make the staggered transition working.',
);
}
return el.dataset.index * this.delay;
},
},
};
</script>

Vue.js + Avoriaz : how to test a watcher?

I am trying to test the following component w Avoriaz, but upon props change , the action in watch: {} is not triggered
ItemComponent.vue
switch checkbox
✗ calls store action updateList when item checkbox is switched
AssertionError: expected false to equal true
at Context.<anonymous> (webpack:///test/unit/specs/components/ItemComponent.spec.js:35:47 <- index.js:25510:48)
thanks for feedback
ItemComponent.vue
<template>
<li :class="{ 'removed': item.checked }">
<div class="checkbox">
<label>
<input type="checkbox" v-model="item.checked"> {{ item.text }}
</label>
</div>
</li>
</template>
<script>
import { mapActions } from 'vuex'
export default {
props: ['item', 'id'],
methods: mapActions(['updateList']),
watch: {
'item.checked': function () {
this.updateList(this.id)
}
}
}
</script>
here is my component test
ItemComponent.spec.js
import Vue from 'vue'
import ItemComponent from '#/components/ItemComponent'
import Vuex from 'vuex'
import sinon from 'sinon'
import { mount } from 'avoriaz'
Vue.use(Vuex)
describe('ItemComponent.vue', () => {
let actions
let store
beforeEach(() => {
actions = {
updateList: sinon.stub()
}
store = new Vuex.Store({
state: {},
actions
})
})
describe('switch checkbox', () => {
it('calls store action updateList when item checkbox is switched', () => {
const id = '3'
const item = { text: 'Bananas', checked: true }
const wrapper = mount(ItemComponent, { propsData: { item, id }, store })
// switch item checked to false
wrapper.setProps({ item: { text: 'Bananas', checked: false } })
expect(wrapper.vm.$props.item.checked).to.equal(false)
expect(actions.updateList.calledOnce).to.equal(true)
})
})
})
U mistaked the prop,use :checked instead
I should write my expect(actions.updateList() . within a $nextTick block
describe('switch checkbox', () => {
it('calls store action updateList when item checkbox is switched', (done) => {
const id = '3'
const item = { text: 'Bananas', checked: true }
const wrapper = mount(ItemComponent, { propsData: { item, id }, store })
// switch item.checked to false
wrapper.setProps({ item: { text: 'Bananas', checked: false } })
expect(wrapper.vm.$props.item.checked).to.equal(false)
wrapper.find('input')[0].trigger('input')
wrapper.vm.$nextTick(() => {
expect(actions.updateList.calledOnce).to.equal(true)
done()
})
})
})
then my test is OK
ItemComponent.vue
switch checkbox
✓ calls store action updateList when item checkbox is switched

Ember.js - doing it right (structure, includes, general questions)

I'm playing around with ember.js and am stuck somehow finding out how to build up the structure the right way. I could follow all examples, but have some problems putting them all together.
I'm using require.js and handlebars.
My directory structure looks like this:
- app
- - controllers
- - css
- - helpers
- - lib
- - models
- - routes
- - templates
- - - partials
- - views
My application.js looks like this:
require.config({
paths:{
jquery:'lib/jquery-1.7.2',
handlebars:'lib/handlebars',
ember:'lib/ember',
ember_data:'lib/ember-data',
text:'lib/requireJS/text',
md5:'lib/md5',
spin:'lib/spin'
},
shim:{
'ember':{
deps:[ 'jquery', 'handlebars'],
exports:'Ember'
},
'ember_data':{
deps:[ 'ember'],
exports:'DS'
}
},
waitSeconds:15
});
define('application'
,[
// Routes
'routes/app_router'
// Controller
,'controllers/application_controller'
// Views
,'views/application_view'
,'views/category/category_list_view'
// Libraries
,'jquery'
,'handlebars'
,'ember'
,'ember_data'
,'spin'
]
, function (
// Router
Router
// Controller
,ApplicationController
// Views
,ApplicationView
,CategoryListView
// Models
,Category
,Product
)
{
return Ember.Application.create({
VERSION: '1.0.0'
,rootElement:'#main'
// Load Router
,Router:Router
// Load Controllers
,ApplicationController:ApplicationController
// Load associated Views
,ApplicationView:ApplicationView
,CategoryListView:CategoryListView
// Load Models
,Category:Category
,Product:Product
//Persistence Layer,using default RESTAdapter in ember-data.js.
,store:DS.Store.create({
revision:10
,adapter:DS.RESTAdapter.create({
bulkCommit:false
,serializer:DS.Serializer.create({
primaryKey:function (type) {
return type.pk;
}
})
,mappings:{
//categories:Category
}
,namespace:'api'
,url: "https://example.org"
})
})
,ready:function () {
}
});
}
);
Then my application controller
define(
'controllers/application_controller'
,['ember' ],
function () {
return Ember.Controller.extend({
init: function() {
}
});
}
);
The application view:
define('views/application_view', [
'text!templates/application.html',
'ember'
],
function(Application_markup) {
return Ember.View.extend({
template: Ember.Handlebars.compile( Application_markup ),
elementId: 'container',
didInsertElement: function() {
this.$().hide().show("slow");
}
});
}
);
And, finally, the application.html template
<div id="container">
<div id="header">
FOO BAR
</div>
<div id="navigation">
{{outlet mainNavigation}}
</div>
<div id="content">
</div>
<div id="footer">
</div>
</div>
What I am trying to do now is to include another template into the main application template (category_list). I guess I either have to do this in the HTML template itself, or in the application view - but in case of the latter one I don't know how to configure/parse/bind more than one template.
What is the best practice of building individual, independent, modular templates and to put them all together? Where exactly should this happen?
Or is this even a wrong approach of using ember.js?
Maybe one of you could make some things more clear to me.
Thanks.
EDIT #1
app_router.js
define('routes/app_router',
['ember' ],
function () {
return Em.Router.extend({
enableLogging:true, //useful for development
/* location property: 'hash': Uses URL fragment identifiers (like #/blog/1) for routing.
'history': Uses the browser's history.pushstate API for routing. Only works in modern browsers with pushstate support.
'none': Does not read or set the browser URL, but still allows for routing to happen. Useful for testing.*/
location:'hash',
/* location: 'history',
rootURL:'/app',*/
root:Ember.Route.extend({
index:Ember.Route.extend({
route:'/'
/*,connectOutlets:function (router) {
//Render application View ,sign in.
v = router.get('applicationController').get('view');
if (v) v.remove();
App.router.get('applicationController').set('loggedin', false);
router.get('applicationController').connectOutlet({name:'login', outletName:'loginform'});
router.get('loginController').enterLogin();
}*/
})
/*,contacts:Em.Route.extend({
route:'/contacts',
showContact:function (router, event) {
router.transitionTo('contacts.contact.index', event.context);
},
showNewContact:function (router) {
router.transitionTo('contacts.newContact', {});
},
logout:function (router) {
jQuery.ajax({
url:'/site/logout',
type:'POST',
success:function (response) {
if (!response.authenticated) {
router.get('applicationController').set('loggedin', false).get('view').remove();
router.transitionTo('root.index', {});
}
}
})
},
index:Em.Route.extend({
route:'/',
connectOutlets:function (router) {
if (router.get('applicationController').get('loggedin'))
router.get('applicationController').connectOutlet('contacts', App.store.findAll(App.Contact));
else router.transitionTo('root.index');
}
}),
contact:Em.Route.extend({
route:'/contact',
index:Em.Route.extend({
route:'/:contact_id',
deserialize:function (router, urlParams) {
return App.store.find(App.Contact, urlParams.contact_id);
debugger;
},
showEdit:function (router) {
router.transitionTo('contacts.contact.edit');
},
connectOutlets:function (router, context) {
if (router.get('applicationController').get('loggedin'))
router.get('contactsController').connectOutlet('contact', context);
else router.transitionTo('root.index');
}
}),
edit:Em.Route.extend({
route:'edit',
cancelEdit:function (router) {
router.transitionTo('contacts.contact.index');
},
connectOutlets:function (router) {
if (router.get('applicationController').get('loggedin')) {
var contactsController = router.get('contactsController');
contactsController.connectOutlet('editContact', router.get('contactController').get('content'));
router.get('editContactController').enterEditing();
} else router.transitionTo('root.index');
},
exit:function (router) {
router.get('editContactController').exitEditing();
}
})
}),
newContact:Em.Route.extend({
route:'/contacts/new',
cancelEdit:function (router) {
router.transitionTo('contacts.index');
},
connectOutlets:function (router) {
if (router.get('applicationController').get('loggedin')) {
router.get('contactsController').connectOutlet('editContact', {});
router.get('editContactController').enterEditing();
} else router.transitionTo('root.index');
},
exit:function (router) {
router.get('editContactController').exitEditing();
}
})
})*/
})
});
}
);
EDIT #2
I changed the router now as follow, but it does not do anything.
define('routes/apps_router', ['ember'],
function () {
return Em.Router.extend({
enableLogging:true
,location:'hash'
,map: function (match) {
match("/").to("CategoryList", function (match) {
match("/").to("mainNavigation");
});
}
,root:Ember.Route.extend({
index:Ember.Route.extend({
route:'/'
,renderTemplates: function() {
this.render('mainNavigation', {
into: 'CategoryList'
});
}
// ....
});
}
);
Kind regards,
Christopher
if you use the latest release of ember with v2 router, you can do something like this:
App.Router.map(function (match) {
match("/").to("categoryList", function (match) {
match("/").to("foo");
});
});
In your catergoryList template, put an {{outlet}} (you can optionally name it)
Then, your route for the template you want to insert into catergoryList will be like this:
App.fooRouter = Ember.Router.extend({
renderTemplates:function () {
this.render('foo', {
into:'catergoryList'
});
}
})
A good example of this in practice can be found here: https://github.com/sh4n3d4v15/ember-todos