Vuelidate, can I inherit a custom method via mixin? - validation

Using Veulidate, using VueJS 2 on a project built using Vue CLI, I'm simply trying to using a custom method for the purpose of validating a phone number. The method is coming from a global mixin located in main.js.
main.js
Vue.mixin({
methods: {
vd_phone(val) {
var phonePattern = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;
return phonePattern.test(val) ? true : false
}
});
form.vue
validations: {
phone: {
required,
phone: this.vd_phone
}
}
Seems simple enough, right? Over and over, I get Cannot read property of 'vd_phone' of undefined. Tried vd_phone, this.vd_phone, this.vd_phone(), etc..
Also tried putting the method into a global methods option (instead of a mixin) and trying to access it via $root like this:
main.js
var vm = new Vue({
router, el: '#app', store,
methods: {
vd_phone() {
var phonePattern = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;
return phonePattern.test(val) ? true : false;
}
},
render: h => h(App)
});
Same problem! In my form.vue file I attempted accessing this method using this.$root.vd_phone, $root.vd_phone, etc.. no dice.
This is all I found on the topic: https://github.com/vuelidate/vuelidate/issues/308, but this seems to talk about inheriting entire validator properties - not just a method.
Any help is appreciated.

You're using a factory pattern to instantiate a function from it's source for use in other files. To do this you must export from the source file so other files can import it, like this:
main.js
export default {
vd_phone(val) {
var phonePattern = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;
return phonePattern.test(val) ? true : false;
}
}
Then import the file where ever you need that function, and you will have access to it.

Related

NativeScript vue, vuex and urlhandler

Edit
I'm using https://github.com/hypery2k/nativescript-urlhandler to open a deep link within my app - using NativeScript vue, and vuex. It seems that in order to get at the methods needed to do routing [$navigateTo etc] this plugin needs to be set up slightly differently from the examples given in docs.
import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);
import { handleOpenURL } from 'nativescript-urlhandler';
new Vue({
mounted() {
handleOpenURL( (appURL) => {
console.log(appURL)
// Settings is the variable that equals the component - in this case settings.
this.$navigateTo(Settings);
});
},
render: h => h("frame", [h(Home)]),
store: ccStore
}).$start();
handleOpenURL needs to be called within Mounted - then you can parse out the appURL and reference the page (component) that you wish to navigate to. I have been advised against calling handleOpenURL from within router - but I'm not sure why, and it works without error - and I have access to the methods for routing... so if anyone knows if this is a bad idea - please let me know :) Thanks!
All the stuff below that I wrote before has probably confused things - I'm referencing components within my vuex store to make them easily available from the router.
This is based on a solution by https://github.com/Spacarar - it can be found here: https://github.com/geodav-tech/vue-nativescript-router-example. It's a great solution because you don't have to include every single component within each component to use in navigation - it gives an almost vue router like experience.
I'm using https://github.com/hypery2k/nativescript-urlhandler to open a deep link within my app - however, I'm having problems opening the link.
In my app.js file, I have the following:
import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);
....
import { handleOpenURL } from 'nativescript-urlhandler';
import ccStore from './store/store';
handleOpenURL(function(appURL) {
// I have hardwired 'Settings' in for testing purposes - but this would be the appURL
ccStore.dispatch('openAppURL', 'Settings');
});
....
new Vue({
render: h => h("frame", [h(Home)]),
store: ccStore
}).$start();
I'm storing the route state within vuex, and have various methods which work (clicking on a link loads the component). However, handleOpenURL exists outside of vue... so I've had to access vuex directly from within the handleOpenURL method. I've created an action specifically for this case - openAppURL.. it does exactly the same thing as my other methods (although I've consolidated it).
When clicking on an app link, I am NOT taken to the page within the app. I have put a console log within openAppURL and can see it is being called, and the correct route object is returned... it just doesn't open the page. The SetTimeOut is used because nextTick isn't available from within vuex.
I am at a loss on how to get the page to appear...
const ccStore = new Vuex.Store({
state: {
user: {
authToken: null,
refreshToken: null,
},
routes: [
{
name: "Home",
component: Home
},
{
name: "Log In",
component: Login
},
...
],
currentRoute: {
//INITIALIZE THIS WITH YOUR HOME PAGE
name: "Home",
component: Home //COMPONENT
},
history: [],
},
mutations: {
navigateTo(state, newRoute, options) {
state.history.push({
route: newRoute,
options
});
},
},
actions: {
openAppURL({state, commit}, routeName ) {
const URL = state.routes[state.routes.map( (route) => {
return route.name;
}).indexOf(routeName)];
return setTimeout(() => {
commit('navigateTo', URL, { animated: false, clearHistory: true });
}, 10000);
},
....
}
etc....
I have been advised to post my findings as the answer and mark it as correct. In order to use nativescript-urlhandler with vue, you must initialise the handler from within vue's mounted life cycle hook. Please see above for greater detail.
import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);
import Settings from "~/components/Settings";
import { handleOpenURL } from 'nativescript-urlhandler';
new Vue({
mounted() {
handleOpenURL( (appURL) => {
console.log(appURL) // here you can get your appURL path etc and map it to a component... eg path === 'Settings. In this example I've just hardwired it in.
this.$navigateTo(Settings);
});
},
render: h => h("frame", [h(Home)]),
store: ccStore
}).$start();

Laravel & Vuejs mixins : how to attribute a new value to shared variable?

I can use the mixin variables test and the method changeTest, when when I attribute a new value to the variable test, it's only applied in one component. How to have it changed globally, on all components using it ?
My mixins are set in the file resources/js/mixins.js:
export default {
data() {
return {
test: 'foo',
};
},
methods: {
changeTest(v) {
this.test = v;
}
}
}
Then, I have my two components comp1.vue and comp2.vue in resources/js/components/, both looking like this:
<template>
<div>
{{ test }}
</div>
</template>
<script>
import myMixins from '../mixins'
export default {
mixins: [ myMixins ],
}
</script>
Both components are in my home.blade.php like this:
#extends('layouts.app')
#section('content')
<comp1></comp1>
<comp2></comp2>
#ensection
for making a common variable (state) between all instances in vue.js you can use vuex. it's so simple, just add vuex to your packages and make an instance like this:
import Vuex from 'vuex'
const store = new Vuex.Store({
state: {
test: 'foo',
},
mutations: {
setTest(state, payload) {
state.test = payload
}
},
});
now you need to add this store to your main vue instance:
import Vue from 'vue'
Vue.use(Vuex);
let vm = new Vue({
el: '#app',
store,
// ...
});
all done. now in every component you can access the states by this.$store.state. for making life easier, you can define a computed variable like this:
computed: {
test() {
return this.$store.state.test
}
}
to change the state you just need to commit the setTest mutation. you have to add this mutation to methods and simply call it like this:
methods: {
...Vuex.mapMutations(['setTest']),
myMethod() {
// do this
this.setTest('some value');
// do that
}
}
you can also make a global mixin like i told you before to add this computed and mutation to every instance like this: (add this before make the main vue instance)
Vue.mixin({
computed: {
test() {
return this.$store.state.test
}
},
methods: {
...Vuex.mapMutations(['setTest']),
}
});
but i don't recommend to do this because when the project grow big, it gets so hard to avoid name confusion. it's better to make them separately for each component to chose proper names.
you can use mixin method on main Vue instance like this:
import Vue from 'vue'
import MyMixin from './mixins.js'
Vue.mixin(MyMixin);
It will apply this mixin for all instance no matter how deep they are.

Updating vuejs component with ajax call from the parent

New to VueJs. I'm wondering how/where would I make an Ajax call to pull data dynamically down to populate the following Vue table?
https://jsfiddle.net/yyx990803/xkkbfL3L/?utm_source=website&utm_medium=embed&utm_campaign=xkkbfL3L
I've (roughly) modified the example above as follows:
var demo = new Vue({
el: '#demo',
data: {
searchQuery: '',
gridColumns: ['name', 'power'],
gridData: []
},
methods: {
fetchUsers: function() {
...
// ajax call using axiom, fetches data into gridData like this:
axios.get('http://localhost/url')
.then(function(response) {
this.gridData = response.data;
})
.catch(function(error) { console.log("error"); })
...
}
},
created: function() {
this.fetchUsers();
}
})
I'm trying to incorporate the ajax pieces from here:
https://jsfiddle.net/chrisvfritz/aomd3y9n/
I've added the fetchUser method which makes the ajax call to pull the data down. I'm able to pull down my data and print it to the console using both fetch and axiom, so I know that part works.
However, my data never appears or updates. The table loads blank. I think it has something to do with me putting the method and created hook on the Vue model object (demo), rather than on the component itself. But I'm not quite sure how to modify the example to resolve it, as the example passes the data in from the parent.
Can someone give me some guidance?
You problem is right over here:
.then(function(response) {
this.gridData = response.data;
})
Within your anonymous function within your then you don't have the context you expect. The most simple solution is adding a .bind(this) to the method.
.then(function(response) {
this.gridData = response.data;
}.bind(this))
By adding it your method body will be aware of the outer context and you can access your components data.

How do I use vue-resource v-links inside a vueify component?

When using v-link="{ path: '/add' }" in my vueify (used with Laravel) component, I get a v-link can only be used inside a router-enabled app. or a <router-view> can only be used inside a router-enabled app. error.
Here is my main.js: http://laravel.io/bin/Kkj27
My code seems very similar to the example provided for nestedRoutes, I am not sure why this is not working.
This is all a little confusing to me (best practices for structuring Vue.js single page apps) but this is essentially what I did to make it work:
Vue.component('Todo', Todo);
And removing this whole thing:
var TodoApp = new Vue({
el: '#app',
components: { Todo }
});
After this, I can refer to the Todo component in the router.map function.
router.map({
'/': {
component: Todo,
subRoutes: {
'/bar': {
...
},
'/baz': {
...
}
}
}
})

Loading "knockout.mapping" plugin using require.js

I am creating an MVC3 application, with requireJS. In my views I need to convert the Model object into a knockout viewmodel object. So I need to use knockout and knockout.mapping libraries.
My application is designed in the following way,
1). All the script files are categorized into folders
Scripts/app/home/ - contains the scripts for the views in Home controller.
Scripts/lib/ - contains the scripts like jQuery, knockout,knockout.mapping, requirejs etc
2). In the "_Layout.cshtml" I am referencing "require.js" like this.
<script src="#Url.Content("~/Scripts/lib/require.js")" type="text/javascript"></script>
3). To configure the require.js settings I am using a different script file called "common.js" (Scripts/lib/common.js)
require.config(
{
baseUrl: "/Scripts/",
paths:{
jquery: "lib/jquery-2.0.3",
ko: "lib/knockout-2.3.0",
komapping: "lib/knockout.mapping"
}
});
4). This is my index.js file which is in 'Scripts/app/home/"
define(['ko', 'komapping'], function (ko, komapping) {
var person = function () {
var self = this;
self.getPersonViewModel = function (data) {
return ko.mapping.fromJS(data); ;
};
};
return { Person: person };
});
5). This is my "Index" action method in the "Home" controller
public ActionResult Index()
{
var person = new Person
{
Id = 1,
Name = "John",
Addresses = new List<Address>(new[]{new Address{Country = "Country 1", City = "City 1"}})
};
return View(person);
}
6). Finally this is my "Index" view
#model MMS.Web.Models.Person
<script type="text/javascript">
require(["/Scripts/common/common.js"], function () {
require(["app/home/index"], function (indexJS) {
var person = new indexJS.Person();
var vm = person.getPersonViewModel(#Html.Raw(Json.Encode(Model)));
});
});
</script>
The problem which I am facing is when loading the index.js file, I get a script error that the knockout.js cannot be loaded.
Failed to load resource: the server responded with a status of 404 (Not Found) - http:///Scripts/knockout.js
But if I remove the dependency of "komapping" inside the "index.js" file it loads correctly, but then I cannot use the mapping functionality.
I had a look inside these links, but couldn't find a solution,
Knockout.js mapping plugin with require.js and
https://github.com/SteveSanderson/knockout.mapping/issues/57
Your help, suggestions are much appreciated. Thanks!
I had the same issue. The problem is that the knockout.mapping defines a knockout dependency, so you need to satisfy this one when you load the script.
Here is how you should load your mapping stuff
require.config(
{
baseUrl: "/Scripts/",
paths:{
jquery: "lib/jquery-2.0.3",
knockout: "lib/knockout-2.3.0",
komapping: "lib/knockout.mapping"
},
shim: {
komapping: {
deps: ['knockout'],
exports: 'komapping'
}
}
});
Then in my case, I use an index.js file with a requirejs call like the following
requirejs(['jquery', 'knockout', 'komapping'], function($, ko, komapping){
ko.mapping = komapping;
//Do other stuff here
});

Resources