Adding radio buttons to Laravel Spark - Vue component page - vue.js

I tried to stay away from the Vue components of Spark as much as possible but I discovered I had to implement a certain mail settings so I can't hold it much longer.
Luckily the Spark documentation contains a small cookbook for adding profile fields:
https://spark.laravel.com/docs/4.0/adding-profile-fields
Most parts are within my (limited PHP) comfort zone:
First the blade php:
Mail settings
<div class="col-md-6">
<label class="radio-inline"><input type="radio" value="profile" v-model="form.type" name="profile">Profile</label>
<label class="radio-inline"><input type="radio" value="website" v-model="form.type" name="website">Website</label>
<label class="radio-inline"><input type="radio" value="combined" v-model="form.type" name="combined">Combined</label>
<span class="help-block" v-show="form.errors.has('mail-settings')">
#{{ form.errors.get('mail-settings') }}
</span>
</div>
</div>
Which is integrated:
<!-- Update Mail settings -->
#include('settings.profile.update-mail-settings')
So as can be seen in the previous code block, I wish to store the result of 3 radio buttons.
However the linked Vue js file is giving my headaches:
Vue.component('update-mail-settings', {
props: ['user'],
data() {
return {
form: new SparkForm({
profile: ''
website: ''
combined: ''
})
};
},
mounted() {
this.form.mailsettings = this.user.mailsettings;
},
methods: {
update() {
Spark.put('/settings/profile/mail-settings', this.form)
.then(response => {
Bus.$emit('updateUser');
});
}
}
});
But how on earth do I integrate the radio buttons in the SparkForm?

In Vue, data binding occurs when you v-model to the object by name. Or in other words, you call v-model="object.property" on an input. When the user fills out the form, the value of form.type will match the form input. So simply change your form object to read:
data() {
return {
form: new SparkForm({
type: '' <- this can now be v-modeled to "form.type"
})
};
},
Your radio buttons don't need to change because they are bound correctly: v-model="form.type"
https://v2.vuejs.org/v2/guide/forms.html#Radio

Related

Vue - Select all checkbox

I'm relatively new to Vue so bare with me on this.
I have a v-for which produces a list of checkboxes, these all individually function correctly if I were to click on them separately, what I am after, like the title says is a select all checkbox to sit ontop which selects all in the list, but I'm running into a few issues which I don't understand, see relevant code below:
new Vue({
el: "#lister-app",
mixins: [pagination, baseDownloadParent],
components: { selectField, articleItem, documentItem },
data: {
facets: {},
isCheckAll: false,
},
computed: {
getFacets() {
return this.facets;
},
getFacetsLength() {
return this.facets.length;
},
},
methods: {
toggleSelect(item, facet) {
if (!this.params[facet.name]) Vue.set(this.params, facet.name, []);
const existElem = this.params[facet.name].findIndex((el) => {
return el === item.identifier;
});
if (existElem !== -1) this.params[facet.name].splice(existElem, 1);
else this.params[facet.name].push(item.identifier);
},
checkAll(){
console.log('FunctionWhichChecksAll');
},
},
});
<label class="option-checkbox" for="Select all">
<input id="Select all" class="option-checkbox__input" type="checkbox" #click='checkAll()' v-model='isCheckAll'>
<span class="option-checkbox__text">Select all</span>
<span class="option-checkbox__icon"></span>
</label>
<option-field inline-template v-for="(item, i) in facet.items" :for="item.name" :key="i + item.name">
<label class="option-checkbox">
<input :id="item.name" class="option-checkbox__input" type="checkbox" v-model="checked" #change="toggleSelect(item, facet)">
<span class="option-checkbox__text">{{item.name}} </span>
<span class="option-checkbox__icon"></span>
</label>
</option-field>
What I am picturing is as piece of script which is inside the checkAll() function?
Any help would be appreciated, thank you in advance.
Here is a working demo, based on your code (simplified):
https://stackblitz.com/edit/vue-prghrq?file=src%2FApp.vue
Checkboxes in Vue can sometimes be a mess, when you combine v-model with #click handlers and especially if you have a check-all field. That's why I usually don't use v-models for it. Using only the :checked value as a one-way binding makes it easier to read and to maintain. With the click handler you can then update the state of each entry.

Vue input event not capturing entire field

I have a vue component that adds a search bar and search bar functionality. It contains this line:
<input class="input" type="text" placeholder="Address" v-model="searchQuery" v-on:input="(event) => this.$emit('queryChange', event)">
This captures the text in the search bar and emits it.
In my vue, this triggers my updateSearchQuery function:
this.searchQuery = event.data which merely saves the users input in the searchQuery property in my vue. Everything works fine when I do this, until, I make a search and then, make another call using the same this.searchQuery data.
For example, I'm trying to filter results with the search query '956'. I enter it and this call is made: GET /users?cp=1&pp=20&se=956, just like it should. Then after the page loads, if I go to page 2 of the results, this is the call that is made to the server: GET /users?cp=2&pp=20&se=6. Instead of saving 956 as the queryStr in the the view, it only saves the most recent character entered, instead of the entire content of the serch text.
This happens every time I type in multiple characters as a search query, and then make another call to the server using the unchanged this.searchQuery variable. If my initial search query is only a single character, it works just fine.
What am I doing wrong here? How can I emit the entirety of the text in the search bar, after any change, so that I can always save the whole search query, instead of the just the most recent change?
EDIT: I've add some more code below so the data flow is easier to follow:
Here is the template and script for the search component:
<template>
<div class="level-item">
<div class="field has-addons">
<div class="control">
<input class="input" type="text" placeholder="Address" v-model.lazy="searchQuery" v-on:input="(event) => this.$emit('queryChange', event)">
</div>
<div class="control">
<div class="button is-light" #click="clearInput">
<span class="icon is-small">
<i class="fa fa-times" style="color:#ffaaaa"></i>
</span>
</div>
</div>
<div class="control">
<button class="button is-info" #click="onSearch(searchQuery)">Search</button>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'Search',
props: {onSearch: Function},
data () {
return {
searchQuery: ''
}
},
watch: {},
methods: {
clearInput () {
this.searchQuery = ''
}
}
}
</script>
the emitted queryChange event is caught and listened to in the vue page:
<Search :onSearch="onSearch" v-on:queryChange="updateSearchQuery"> and this triggers the updateSearchQuery function:
updateSearchQuery (event) {
this.searchQuery = event.data
console.log(event.data + ' || event.data')
console.log(this.searchQuery + ' || this.searchQuery')
}
Theoretically, the searchQuery data in my vue should be a copy of the searchQuery data in my component, which is itself merely a copy of whatever the user has input in the search bar.
Then when I make a call to the server I'm using the value in this.searchQuery in my vue:
onSearch (search) {
this.makeServerQuery(1, search)
},
onPaginate (page) {
this.makeServerQuery(page, this.searchQuery)
},
makeServerQuery (page = null, search = null) {
let queryStr = ''
if (page !== null) {
queryStr += '?cp=' + page + '&pp=' + this.perPage
}
if (this.searchQuery !== '') {
queryStr += '&se=' + this.searchQuery
} .....
The on onSearch(search) function is called whenever the search button is pressed. That seems to work fine, because when the button is pressed the entire searchQuery is passed, not just the last change.
An input event's data value appears to be the last typed character, and not the current value of the input. A simple fix is:
#input="$emit('queryChange', searchQuery)"
This works because the model will always be updated before the input event handler runs.
Here's a complete working component example:
<input
v-model="searchQuery"
type="text"
placeholder="Address"
#input="onInput"
/>
export default {
data() {
return { searchQuery: '' };
},
methods: {
onInput() {
console.log(this.searchQuery);
this.$emit('queryChange', this.searchQuery);
},
},
};

Array of inputs, with last field always blank for new add

JSBin and Stackoverflow snippet are below.
I am trying to have a list of input components. If all input components are filled with a value (not blank), then there should be a "new blank field" visible at the end for the user to type into. When he types into it, it should make this field apart of the list above it, maintaining focus in it.
However the problem I'm having is, focus maintains in the new field, and never moves into the array. Here is my code:
JSBIN and stackoverflow snippet - https://jsbin.com/cudabicese/1/edit?html,js,output
const app = new Vue({
el: '#app',
data: {
inputs: [
{ id:'foo', value:'foo' },
{ id:'bar', value:'bar' }
]
},
methods: {
addRow(e) {
this.inputs.push({
id: Date.now(),
value: e.target.value
})
},
deleteRow(index) {
this.inputs.splice(index, 1)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="app">
<ul>
<li v-for="(input, index) of inputs">
<input type="text" v-model="input.value">
</li>
<li v-if="inputs.filter(input => !!input.value).length">
<input type="text" #input="addRow">
</li>
</ul>
</div>
I'd recommend you put the input for the list within a computed function vs directly using the data. The examples at https://v2.vuejs.org/v2/examples/ are a good place to start.

How can I upload image in a link on the vue component?

My component vue like this :
<template>
<div>
<ul class="list-inline list-photo">
<li v-for="item in items">
<div class="thumbnail" v-if="clicked[item]">
<img src="https://myshop.co.id/img/no-image.jpg" alt="">
<span class="fa fa-check-circle"></span>
</div>
<a v-else href="javascript:;" class="thumbnail thumbnail-upload"
title="Add Image" #click="addPhoto(item)">
<span class="fa fa-plus fa-2x"></span>
</a>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['state', 'product'],
data() {
return {
items: [1, 2, 3, 4, 5],
clicked: [] // using an array because your items are numeric
}
}
},
methods: {
addPhoto(item) {
this.$set(this.clicked, item, true)
}
}
}
</script>
If I click a link then it will call method addPhoto
I want if the a link clicked, it will upload image. So it will select the image then upload it and update img with image uploaded.
It looks like the code to upload image will be put in add photo method
I'm still confused to upload image in vue component
How can I solve it?
You can use a component for file picker like this:
<template>
<input v-show="showNative" type="file" :name="name" #change="onFileChanged" :multiple="multiple" :accept="accept"/>
</template>
<script>
export default {
props: {
name: { type: String, required: true },
show: { type: Boolean, Default: false },
multiple: { type: Boolean, default: false },
accept: { type: String, default: "" },
showNative: { type: Boolean, default: false }
},
watch: {
show(value) {
if (value) {
// Resets the file to let <onChange> event to work.
this.$el.value = "";
// Opens select file system dialog.
this.$el.click();
// Resets the show property (sync technique), in order to let the user to reopen the dialog.
this.$emit('update:show', false);
}
}
},
methods: {
onFileChanged(event) {
var files = event.target.files || event.dataTransfer.files;
if (!files.length) {
return;
}
var formData = new FormData();
// Maps the provided name to files.
formData.append(this.name, this.multiple ? files : files[0]);
// Returns formData (which can be sent to the backend) and optional, the selected files (parent component may need some information about files).
this.$emit("files", formData, files);
}
}
}
</script>
And here some information how to use it:
import the component -> declare the directive.
provide a -> is used for the formData creation (is the name which is going to backend).
to display it us the property
Note: sync recommended if needed to be opened multiple times in the same page. Check the bottom examples. ( /!\ Vue 2.3 required for sync /!\ )
listen to #files event to get an array of selected files as parameter
if you want to use it as multiple file select, then provide the property as true.
use prop to filter the files (valid accept types: HTML Input="file" Accept Attribute File Type (CSV)).
when is set to true, the component displays 'select file' button (input type file), otherwise it is hidden, and windows displayed by Js.
ex:
Single select
<file-upload name="fooImport" #files="selectedFile" :show.sync="true" />
ex:
Multiple select
<file-upload name="barUpload" #files="selectedFiles" :show.sync="displayUpload" accept="text/plain, .pdf" />

vuejs: Trying to focus the input using v-el directive

I am creating a wizard login form where the Mobile Number is first entered and
password is entered next.
Here am trying to focus the password input using
this.$$.passwordInput.focus()
however if am getting the error given below
Uncaught TypeError: Cannot read property 'focus' of undefined
The full code is below
index.html
<div id="login">
<div v-if="flow.mobile">
<form v-on="submit: checkmobile">
<p>
Mobile Number<br>
<input type="text" v-model="mobile_number" v-el="mobileNumber">
</p>
</form>
</div>
<div v-if="flow.password">
<form v-on="submit: checkpassword">
<p>
Password<br>
<input type="password" v-model="password" v-el="passwordInput">
</p>
</form>
</div>
script.js
var demo = new Vue({
el: '#login',
data: {
flow: {
mobile: true,
password: false
}
},
methods: {
checkmobile: function(e) {
e.preventDefault();
this.flow.mobile = false;
this.flow.password = true;
this.$$.passwordInput.focus();
},
checkpassword: function(e) {
e.preventDefault();
}
}
});
Your passwordInput is inside a v-if block, which only gets rendered when you set flow.password to true; However Vue uses asynchronous rendering, so the v-if block will not be rendered immediately. You can use Vue.nextTick to wait until it does:
this.flow.password = true;
var self = this;
Vue.nextTick(function () {
self.$$.passwordInput.focus();
});
Read the guide about async rendering for more details.
In Vue.js 2.x you can create your own directive to focus a field automatically:
Vue.directive('focus', {
inserted: function (el) {
el.focus();
},
update: function (el) {
Vue.nextTick(function() {
el.focus();
})
}
})
Then you can use v-focus attribute on inputs and other elements:
<input v-focus>
Working example: https://jsfiddle.net/LukaszWiktor/cap43pdn/
If you are using vuejs 2, you should read this:
https://v2.vuejs.org/v2/guide/migration.html#v-el-and-v-ref-replaced
--
In this case, in your template:
use ref="passwordInput" instead v-el="passwordInput"
and in your method:
this.$refs.passwordInput.focus()
I hope this help you!
Glad this worked for some of you.
I have no idea why, but after trying every conceivable variation of the accepted answer I could not get the $$.ref property when using v-repeat.
I could only access the newly created dom elements like so:
new Vue({
el: '#reporting_create',
data: {
recipients: {
0: {
fname: null,
lname: null,
email: null,
registration: false,
report: false
}
},
curRec:1
},
methods: {
addRecipient: function(){
event.preventDefault();
this.recipients.$add(
this.curRec,
{
fname: null,
lname: null,
email: null,
registration: false,
report: false
}
);
var num = this.curRec;
this.$nextTick(function () {
console.log(this._children[num].$$.rowrec);
newSwitches.find('.switch').bootstrapSwitch();
})
this.curRec++;
}
}})
html:
<template v-repeat="recipients">
<div class="row" v-el="rowrec">
<div>{{$key}}</div>
</div>
</template>
The addRecipients function was called outside the v-repeat so even the suggested answer here did couldn't help
Not sure if there is an issue with doing it this way but it works and I'm tired.
Vue.js 1 works a bit different.
Example:
<textarea v-el:model_message></textarea>
JS:
this.$els.model_message.focus();
If you are using Vue.js 2.0, you should do the following:
<input type="text" v-model="currentItem.name" ref="txtName">
So you can access this input by using the $refs object:
this.$refs.txtName.focus();
I hope it helps.
Vue v2's documentation uses focus as an example in writing custom directives. All of the needed code is supplied with the example, https://v2.vuejs.org/v2/guide/custom-directive.html. First you must register the directive. The link shows how to register it locally on the component.
// Register a global custom directive called `v-focus`
Vue.directive('focus', {
// When the bound element is inserted into the DOM...
inserted: function (el) {
// Focus the element
el.focus()
}
})
Having done this, you are now able to use v-focus on an element:
<input v-focus>
Like so.